Write streams to a Time-Addressable Media Store (TAMS). The output URL is
the store's /flows endpoint. By default every AVStream is written to its
own new Flow and Source; the flow_map option groups streams into a multi
Flow sharing one container, or pins streams to existing Flows, Sources and
multi Flows, e.g. to append a recording to an existing timeline (with
start_timestamp).

Each segment is a self-contained Media Object produced by a fresh instance
of a nested muxer (a raw elementary-stream muxer where one exists, else
MP4, or as forced with the container option: mp4, mov, mpegts, matroska),
cut at the first keyframe after segment_duration. Its bytes are PUT to a
presigned URL allocated by the store, then the segment is registered with
its timerange, ts_offset and last_duration.

Every object after the first starts its timestamps at 0 at the keyframe it
was cut on, with ts_offset set per segment; MPEG-TS PTS are the Flow time
at 90 kHz modulo 2^33, as in the TAMS MPEG-TS application note. In a
shared container, packets of other streams from before a cut are written
to the previous object, which is uploaded once every stream has passed
the cut.

Flows created by the muxer have status awaiting_content until their first
segment is registered, ingesting while being written and closed_complete
once finalized, with avg_bit_rate and max_bit_rate, so that the demuxer can
follow them live.

Assisted-by: Claude Opus 5.5
Signed-off-by: Nick Ryan <[email protected]>
---
 Changelog                    |    2 +-
 configure                    |    1 +
 doc/general_contents.texi    |    2 +-
 doc/muxers.texi              |  165 +++
 libavformat/Makefile         |    2 +
 libavformat/allformats.c     |    1 +
 libavformat/tamsenc.c        | 2580 ++++++++++++++++++++++++++++++++++
 libavformat/tests/.gitignore |    1 +
 libavformat/tests/tamsenc.c  |  634 +++++++++
 libavformat/version.h        |    2 +-
 tests/fate/libavformat.mak   |    4 +
 tests/ref/fate/tamsenc       |   37 +
 12 files changed, 3428 insertions(+), 3 deletions(-)
 create mode 100644 libavformat/tamsenc.c
 create mode 100644 libavformat/tests/tamsenc.c
 create mode 100644 tests/ref/fate/tamsenc

diff --git a/Changelog b/Changelog
index d5df11749c0..4ccaf68d225 100644
--- a/Changelog
+++ b/Changelog
@@ -7,7 +7,7 @@ version <next>:
 - AVS+ (AVS1-P16, Broadcasting profile) support in the Chinese AVS decoder
 - PCM PAMF decoder
 - Super Audio CD (SACD) demuxer
-- TAMS (Time-Addressable Media Store) demuxer
+- TAMS (Time-Addressable Media Store) demuxer and muxer
 
 version 9.1:
 - ASTC image encoding and decoding via libastcenc, with .astc and KTX 1.0 
muxers and demuxers
diff --git a/configure b/configure
index ad9b0f6bb5f..2c1a035bfb5 100755
--- a/configure
+++ b/configure
@@ -3996,6 +3996,7 @@ spdif_muxer_select="adts_header"
 spx_muxer_select="ogg_muxer"
 swf_demuxer_suggest="zlib"
 tak_demuxer_select="tak_parser"
+tams_muxer_select="dump_extra_bsf"
 tee_muxer_select="fifo_muxer"
 truehd_demuxer_select="mlp_parser"
 tg2_muxer_select="mov_muxer"
diff --git a/doc/general_contents.texi b/doc/general_contents.texi
index 32e65fe1c48..04f2d80c45a 100644
--- a/doc/general_contents.texi
+++ b/doc/general_contents.texi
@@ -841,7 +841,7 @@ library:
 @item Super Audio CD (SACD)     @tab   @tab X
 @item SVAG                      @tab   @tab X
     @tab Audio format used in Konami PS2 games.
-@item TAMS (Time-Addressable Media Store) @tab @tab X
+@item TAMS (Time-Addressable Media Store) @tab X @tab X
 @item TDSC                      @tab   @tab X
 @item Text files                @tab   @tab X
 @item THP                       @tab   @tab X
diff --git a/doc/muxers.texi b/doc/muxers.texi
index 16a772818fc..eca29f47217 100644
--- a/doc/muxers.texi
+++ b/doc/muxers.texi
@@ -3908,6 +3908,171 @@ ffmpeg -i INPUT -f streamhash -hash md5 -
 
 See also the @ref{hash} and @ref{framehash} muxers.
 
+@section tams
+
+Time-Addressable Media Store muxer.
+
+This muxer writes audio and video streams to TAMS Flows, as specified in
+@url{https://bbc.github.io/tams/main/index.html, Time-addressable Media Store}.
+
+The output URL must be the store's @code{/flows} collection endpoint, e.g.
+@code{http://tamsEndpoint/flows}. Each input AVStream is written to a TAMS
+Flow: either its own standalone mono Flow, or a member of a multi-Flow
+sharing one physical container, as directed by the @option{flow_map} option.
+A Flow's essence parameters (codec, dimensions, sample rate, etc.) are always
+taken from the mapped AVStream; if @option{flow_map} pins an existing Flow
+(via @code{id=}), its essence parameters are validated against the stream's
+rather than overwritten.
+
+Every segment is a self-contained Media Object written by a fresh instance of
+the container muxer, uploaded to a presigned URL obtained from the store and
+then registered against the Flow. Flows created by the muxer are given the
+@code{status} @code{awaiting_content} until their first segment is registered,
+@code{ingesting} while segments are written and @code{closed_complete} once the
+output is finalized, which lets the TAMS demuxer follow the Flow live. Their
+@code{avg_bit_rate} and @code{max_bit_rate} are set when the output is 
finalized.
+
+The first segment keeps the input's timestamps and every later segment's
+timestamps start at 0 at the keyframe it was cut on, except for MPEG-TS, whose
+PTS are the Flow time at 90 kHz modulo 2^33. The segment's @code{ts_offset}
+maps them onto the Flow timeline. MP4 segments are not fragmented: their edit
+lists keep the tracks in sync and mark the audio priming.
+
+A mono Flow's @code{label}/@code{description} come from that AVStream's
+@code{title}/@code{comment} metadata (settable via
+@option{-metadata:s:@var{streamindex}}); any other stream metadata key
+becomes a Flow tag. A multi-Flow's @code{label}/@code{description}/tags are
+set via the @code{label=}/@code{description=}/@code{tags.@var{name}=} attrs
+on its @code{multi_flow=@var{N}} @option{flow_map} token instead (ignored if
+that token also pins an existing multi-Flow, since a pinned multi-Flow's
+metadata is never modified).
+
+@table @option
+@item flow_map @var{map}
+Space-separated list of tokens describing how AVStreams map to Flows and,
+for multi-Flows, how streams sharing one container map to one multi-Flow's
+@code{flow_collection}. Two kinds of token are accepted:
+
+@table @code
+@item 
flow=streams=@var{index}[,@var{index}...][,id=@var{uuid}[,id=@var{uuid}...]][,source_id=@var{uuid}][,multi_flow=@var{N}]
+Maps one or more AVStream indices to one physical container. @code{id=} may
+repeat, positionally paired with the @code{streams=} indices, to pin each
+mapped stream's Flow to an existing Flow id (rather than creating a new
+Flow); @code{source_id=} sets the @code{source_id} for any newly-created
+Flow among them. A token naming more than one stream requires
+@code{multi_flow=@var{N}} as container sharing is only possible within a
+multi-Flow's @code{flow_collection}; @var{N} is an arbitrary integer
+correlating this token with a @code{multi_flow=@var{N}} token (below)
+describing the multi-Flow itself.
+
+@item 
multi_flow=@var{N},id=@var{uuid}|source_id=@var{uuid}|label=@var{text}|description=@var{text}|tags.@var{name}=@var{text}[,...]
+Sets properties of the multi-Flow correlated by @var{N} with one or more
+@code{flow=...,multi_flow=@var{N}} tokens above. @code{id=} pins it to an
+existing multi-Flow; @code{source_id=} sets the @code{source_id} for a
+newly-created one. @code{tags.@var{name}=@var{text}} may repeat, once per
+tag. This token is only needed to set @code{id=}/@code{source_id=}/
+@code{label=}/@code{description=}/tags; a multi-Flow referenced only via
+@code{multi_flow=@var{N}} on @code{flow=} tokens is otherwise created with
+none of these set.
+@end table
+
+An AVStream index may appear in at most one @code{flow=} token; any stream
+not mentioned in @option{flow_map} (or when @option{flow_map} is omitted
+entirely) defaults to its own standalone mono Flow. Because @code{,} and
+space are the attr and token delimiters, @code{label=}/@code{description=}/
+@code{tags.@var{name}=} values may not contain a comma or a space.
+
+@item container @var{format}
+Force the physical container format for every mapped container. Supported
+values are @code{mp4}, @code{mov}, @code{mpegts} and @code{matroska}, plus
+the codec-specific raw elementary-stream muxers (e.g. @code{h264}). By
+default, a single-stream container uses a raw elementary-stream muxer where
+one exists (Matroska for raw video), and anything else,
+including a multi-stream (multi-Flow) container, uses MP4.
+
+@item start_timestamp @var{timestamp}
+Override the wall-clock timeline origin with an explicit TAMS timestamp
+string (@code{@{seconds@}:@{nanoseconds@}}, TAI-based). By default, the
+current wall-clock time is used.
+
+@item segment_duration @var{seconds}
+Target segment duration in seconds. By default (@code{-1}), a pinned Flow's
+own @code{segment_duration} is used if it has one, else 2 seconds. A segment
+is cut at the first keyframe of the container's first video stream (else its
+first stream) at or after this duration, so the actual segment length also
+depends on the encoder's GOP size.
+
+@item retry_max @var{n}
+Maximum retry attempts for transient HTTP errors talking to the TAMS store.
+Default is 3.
+
+@item retry_backoff @var{microseconds}
+Initial retry backoff, doubling on each subsequent attempt. Default is
+500000 (0.5s).
+@end table
+
+@subsection Examples
+
+Mux a single video stream to its own mono Flow, creating a new Flow with a
+random id:
+@example
+ffmpeg -i INPUT -c:v h264 -f tams http://tamsEndpoint/flows
+@end example
+
+Mux to an existing, pinned Flow, validating the stream's essence parameters
+against it:
+@example
+ffmpeg -i INPUT -c:v h264 -f tams \
+  -flow_map "flow=streams=0,id=<flowId>" http://tamsEndpoint/flows
+@end example
+
+Mux video and audio as a shared-container multi-Flow with a label:
+@example
+ffmpeg -i INPUT -c:v h264 -c:a aac -f tams \
+  -flow_map "flow=streams=0,1,multi_flow=0 multi_flow=0,label=MyProgram" \
+  http://tamsEndpoint/flows
+@end example
+
+Set a mono Flow's label/description/tags from stream metadata:
+@example
+ffmpeg -i INPUT -c:v h264 -metadata:s:0 title="My Video" \
+  -metadata:s:0 comment="A description" -metadata:s:0 priority=high \
+  -f tams http://tamsEndpoint/flows
+@end example
+
+Mux a new mono Flow under an existing, pinned Source:
+@example
+ffmpeg -i INPUT -c:v h264 -f tams \
+  -flow_map "flow=streams=0,source_id=<sourceId>" http://tamsEndpoint/flows
+@end example
+
+Mux video and audio, matching each against an existing multi-Flow's
+@code{flow_collection} by essence type rather than pinning either
+individually:
+@example
+ffmpeg -i INPUT -c:v h264 -c:a aac -f tams \
+  -flow_map "flow=streams=0,multi_flow=0 flow=streams=1,multi_flow=0 \
+             multi_flow=0,id=<multiFlowId>" \
+  http://tamsEndpoint/flows
+@end example
+
+Mux video and audio into one shared container, with each sub-Flow
+individually pinned by position (each @code{id=} matched to the
+corresponding @code{streams=} index, in list order) and grouped under an
+existing multi-Flow:
+@example
+ffmpeg -i INPUT -c:v h264 -c:a aac -f tams \
+  -flow_map "flow=streams=0,1,id=<videoFlowId>,id=<audioFlowId>,multi_flow=0 \
+             multi_flow=0,id=<multiFlowId>" \
+  http://tamsEndpoint/flows
+@end example
+
+Mux to a TAMS endpoint that requires OAuth2 bearer authentication:
+@example
+ffmpeg -i INPUT -c:v h264 -f tams \
+  -headers "Authorization: Bearer <token>" http://tamsEndpoint/flows
+@end example
+
 @anchor{tee}
 @section tee
 
diff --git a/libavformat/Makefile b/libavformat/Makefile
index a2023d96922..f10cf04c0fd 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -600,6 +600,7 @@ OBJS-$(CONFIG_SWF_DEMUXER)               += swfdec.o swf.o
 OBJS-$(CONFIG_SWF_MUXER)                 += swfenc.o swf.o
 OBJS-$(CONFIG_TAK_DEMUXER)               += takdec.o apetag.o img2.o rawdec.o
 OBJS-$(CONFIG_TAMS_DEMUXER)              += tamsdec.o tams.o
+OBJS-$(CONFIG_TAMS_MUXER)                += tamsenc.o tams.o
 OBJS-$(CONFIG_TEDCAPTIONS_DEMUXER)       += tedcaptionsdec.o subtitles.o
 OBJS-$(CONFIG_TEE_MUXER)                 += tee.o tee_common.o
 OBJS-$(CONFIG_THP_DEMUXER)               += thp.o
@@ -807,6 +808,7 @@ TESTPROGS-$(CONFIG_MPEGTS_DEMUXER)       += mpegts_probe
 TESTPROGS-$(CONFIG_OGG_MUXER)            += ogg_pages
 TESTPROGS-$(CONFIG_TAMS_DEMUXER)         += tams
 TESTPROGS-$(CONFIG_TAMS_DEMUXER)         += tamsdec
+TESTPROGS-$(CONFIG_TAMS_MUXER)           += tamsenc
 
 TOOLS     = aviocat                                                     \
             ismindex                                                    \
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 0d6808dfb25..f2860a721f0 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -478,6 +478,7 @@ extern const FFInputFormat  ff_swf_demuxer;
 extern const FFOutputFormat ff_swf_muxer;
 extern const FFInputFormat  ff_tak_demuxer;
 extern const FFInputFormat  ff_tams_demuxer;
+extern const FFOutputFormat ff_tams_muxer;
 extern const FFOutputFormat ff_tee_muxer;
 extern const FFInputFormat  ff_tedcaptions_demuxer;
 extern const FFOutputFormat ff_tg2_muxer;
diff --git a/libavformat/tamsenc.c b/libavformat/tamsenc.c
new file mode 100644
index 00000000000..fa758d6f2c8
--- /dev/null
+++ b/libavformat/tamsenc.c
@@ -0,0 +1,2580 @@
+/*
+ * Copyright (C) 2026 Hoot Works Ltd
+ * Author    (C) 2026 Nick Ryan <[email protected]>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * TAMS (Time-Addressable Media Store) muxer.
+ *
+ * Muxes one or more TAMS Flows
+ *
+ * References
+ * https://bbc.github.io/tams/main/index.html
+ *
+ * @author Nick Ryan
+ */
+
+#include "avformat.h"
+#include "internal.h"
+#include "mux.h"
+#include "tams.h"
+
+#include "libavutil/avstring.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+#include "libavutil/pixdesc.h"
+#include "libavutil/random_seed.h"
+#include "libavutil/time.h"
+#include "libavutil/uuid.h"
+
+#include <string.h>
+
+typedef struct TAMSFlowContext {
+    int stream_index;    /* index into the owning container's 
sub_ctx->streams[] */
+
+    char flow_id[TAMS_UUID_SIZE];
+    int  has_flow_id;    /* came from -flow_map id= on this token */
+
+    char source_id[TAMS_UUID_SIZE];
+    int  has_source_id;  /* came from -flow_map source_id= on this token */
+
+    TAMSFlow flow;
+    int  created;        /* Flow was created by this muxer */
+} TAMSFlowContext;
+
+/* A segment object whose timerange is known, waiting to be uploaded */
+typedef struct TAMSClosingObject {
+    AVFormatContext *sub_ctx;
+    char *put_url;
+    char *object_id;
+    char put_content_type[128];
+    int64_t start_ns;           /* timerange, relative to c->start_tai_ns */
+    int64_t end_ns;
+    int64_t last_ref_ns;
+    int64_t ts_offset;
+    int nb_pending;             /* streams still to pass end_ns */
+} TAMSClosingObject;
+
+/* one physical container / nested muxer i.e. one 'flow=' token from -flow_map 
*/
+typedef struct TAMSContainerContext {
+    int *stream_indices; /* indices into the parent AVFormatContext's 
streams[] */
+    int  nb_streams;
+
+    const AVOutputFormat *oformat;
+    AVFormatContext *sub_ctx; /* nested muxer for this container's physical 
output */
+
+    TAMSFlowContext *flow_ctxs; /* one entry per stream_indices[], sized 
nb_streams */
+
+    int multi_flow_index; /* the 'multi_flow=N' correlation key, if any */
+    int has_multi_flow;   /* true iff this container belongs to some 
multi-Flow */
+
+    char container_mime[128]; /* this container's resolved Flow.container MIME 
*/
+
+    /*
+     * The Flow that owns this container's storage/segments: its sole mono
+     * Flow when nb_streams==1, else the parent multi-Flow when nb_streams>1
+     * (a shared container is registered once, against the multi, per the
+     * demuxer's container-mapped-sub-flow model. Member mono Flows for a
+     * shared container get an id/essence/role but no container/segments of
+     * their own). Resolved once both mono and multi Flows exist.
+     */
+    char owner_flow_id[TAMS_UUID_SIZE];
+
+    int reference_stream_index; /* sub_ctx stream index used for boundary 
decisions */
+    int64_t segment_duration_ns;
+    int64_t segment_start_ns;   /* relative to c->start_tai_ns */
+    int64_t next_boundary_ns;
+    int64_t segment_end_ns;     /* max pts + duration written to this segment 
*/
+    int has_segment_data;
+
+    /*
+     * Added to every timestamp written to the current object
+     * minus the pts of the reference keyframe that starts it. So each object
+     * starts at 0 (the first object is not shifted) or for
+     * MPEG-TS the shift that makes its PTS the Flow time at 90 kHz modulo 
2^33.
+     */
+    int64_t ts_shift;           /* in ts_shift_tb */
+    AVRational ts_shift_tb;
+
+    int64_t first_ns;           /* first packet timestamp in the current 
object */
+    int64_t last_ref_ns;        /* last reference stream timestamp in the 
current object */
+
+    int64_t segment_index;
+    int error;                  /* sticky: a failed flush leaves sub_ctx 
unusable */
+
+    /*
+     * The object before the last segment cut stays open until every other 
stream has
+     * passed the cut. This allows packets before the cut which still arrive 
to be
+     * stored in the object whose timerange contains them.
+     */
+    TAMSClosingObject prev;
+    int has_prev;
+    int64_t ts_shift_prev;      /* ts_shift of the previous object in 
ts_shift_prev_tb */
+    AVRational ts_shift_prev_tb;
+    uint8_t *passed_cut;        /* per stream array: a packet at or after 
prev.end_ns was seen */
+
+    int64_t total_bytes;        /* for the owner Flow's 
avg_bit_rate/max_bit_rate */
+    int64_t total_ns;
+    int64_t max_bit_rate;       /* bit/s */
+
+    /* storage for the current object, allocated when it starts */
+    char *next_put_url;
+    char *next_object_id;
+    char next_put_content_type[128]; /* from put_url's "content-type", may be 
empty */
+} TAMSContainerContext;
+
+/*
+ * One independent multi-Flow i.e. one distinct 'multi_flow=N' correlation key
+ * referenced by some flow= token(s)
+ */
+typedef struct TAMSMultiFlowContext {
+    int index; /* the N value: an arbitrary correlation key, may be sparse */
+
+    char flow_id[TAMS_UUID_SIZE];
+    int  has_flow_id; /* came from a 'multi_flow=N,id=...' token */
+
+    char source_id[TAMS_UUID_SIZE];
+    int  has_source_id; /* came from a 'multi_flow=N,source_id=...' token */
+
+    char label[256]; /* came from a 'multi_flow=N,label=...' token; ignored if 
has_flow_id */
+    char description[1024]; /* likewise, from 'description=...' */
+
+    TAMSTag tags[TAMS_MAX_TAGS]; /* likewise, from one or more 
'tags.<name>=...' */
+    int  nb_tags;
+
+    TAMSFlow flow;
+    int  created; /* Flow was created by this muxer */
+
+    int *container_indices; /* indices into TAMSMuxContext.container_ctxs[] 
belonging here */
+    int  nb_container_indices;
+} TAMSMultiFlowContext;
+
+typedef struct TAMSMuxContext {
+    const AVClass *class;
+
+    char *flow_map_str;
+    char *container_name;
+    char *start_timestamp_str;
+    char *headers_str;
+    int64_t segment_duration_s; /* -1 = auto */
+    int retry_max;              /* attempts */
+    int64_t retry_backoff_us;
+
+    TAMSContainerContext *container_ctxs;
+    int nb_container_ctxs;
+
+    TAMSMultiFlowContext *multi_flow_ctxs;
+    int nb_multi_flow_ctxs;
+
+    int *stream_to_container;
+    int *stream_to_subindex;
+
+    int64_t start_tai_ns;
+    AVDictionary *avio_opts;
+
+    /* base "/flows" collection URL, derived once from s->url in write_header 
*/
+    char flows_base_url[2048];
+
+    int64_t min_object_timeout_us;
+    int64_t min_presigned_url_timeout_us;
+} TAMSMuxContext;
+
+/*
+ * Per-codec default raw elementary-stream muxer. Used when -container isn't
+ * specified and the container has exactly one stream. Raw video and PCM have
+ * no raw elementary-stream entry: TAMS allows them without a container, but
+ * the ffmpeg TAMS demuxer detects segment formats by probing rather than from
+ * the Flow's container, and their raw forms have no header or sync bytes to
+ * probe. Raw video goes in Matroska, PCM falls through to the mp4 fallback.
+ */
+static const struct {
+    enum AVCodecID codec_id;
+    const char *muxer_name;
+} tams_default_muxers[] = {
+    { AV_CODEC_ID_H264,       "h264"       },
+    { AV_CODEC_ID_HEVC,       "hevc"       },
+    { AV_CODEC_ID_VP8,        "ivf"        },
+    { AV_CODEC_ID_VP9,        "ivf"        },
+    { AV_CODEC_ID_AV1,        "obu"        },
+    { AV_CODEC_ID_MPEG2VIDEO, "mpeg2video" },
+    { AV_CODEC_ID_RAWVIDEO,   "matroska"   },
+    { AV_CODEC_ID_AAC,        "adts"       },
+    { AV_CODEC_ID_MP2,        "mp2"        },
+    { AV_CODEC_ID_MP3,        "mp3"        },
+    { AV_CODEC_ID_AC3,        "ac3"        },
+    { AV_CODEC_ID_EAC3,       "eac3"       },
+    { AV_CODEC_ID_WEBVTT,     "webvtt"     },
+    { AV_CODEC_ID_SUBRIP,     "srt"        },
+};
+
+/*
+ * Container MIME type per nested muxer. mp4 is resolved separately, as its
+ * MIME type depends on the media type of its streams, and a raw
+ * elementary-stream muxer uses its codec's MIME type.
+ */
+static const struct {
+    const char *muxer_name;
+    const char *mime;
+} tams_container_mimes[] = {
+    { "mpegts",   "video/mp2t"       },
+    { "mov",      "video/quicktime"  },
+    { "matroska", "video/x-matroska" },
+    { "mxf",      "application/mxf"  },
+};
+
+static const AVOutputFormat *tams_default_raw_oformat(enum AVCodecID codec_id)
+{
+    for (int i = 0; i < FF_ARRAY_ELEMS(tams_default_muxers); i++)
+        if (tams_default_muxers[i].codec_id == codec_id)
+            return av_guess_format(tams_default_muxers[i].muxer_name, NULL, 
NULL);
+    return NULL;
+}
+
+/*
+ * Resolve oformat using -container if given, else a per-codec raw-ES default
+ * for a single-stream container else MP4 as its edit lists
+ * keep the tracks in sync and mark the audio priming).
+ */
+static int tams_resolve_oformat(AVFormatContext *s, TAMSContainerContext *cc)
+{
+    TAMSMuxContext *c = s->priv_data;
+    const AVOutputFormat *oformat;
+
+    if (c->container_name) {
+        oformat = av_guess_format(c->container_name, NULL, NULL);
+        if (!oformat) {
+            av_log(s, AV_LOG_ERROR, "Unknown -container format '%s'\n", 
c->container_name);
+            return AVERROR_MUXER_NOT_FOUND;
+        }
+        cc->oformat = oformat;
+        return 0;
+    }
+
+    if (cc->nb_streams == 1) {
+        oformat = 
tams_default_raw_oformat(s->streams[cc->stream_indices[0]]->codecpar->codec_id);
+        if (oformat) {
+            cc->oformat = oformat;
+            return 0;
+        }
+    }
+
+    oformat = av_guess_format("mp4", NULL, NULL);
+    if (!oformat) {
+        av_log(s, AV_LOG_ERROR, "mp4 muxer not available for the default 
container\n");
+        return AVERROR_MUXER_NOT_FOUND;
+    }
+    cc->oformat = oformat;
+    return 0;
+}
+
+static int tams_is_valid_uuid(const char *s)
+{
+    AVUUID uu;
+
+    if (av_uuid_parse(s, uu) < 0)
+        return 0;
+    /* av_uuid_parse() skips the separator positions without checking them */
+    return s[8] == '-' && s[13] == '-' && s[18] == '-' && s[23] == '-';
+}
+
+/**
+ * Validate a UUID given in -flow_map and force it to lower case in place as
+ * TAMS only allows lower-case UUIDs.
+ * Returns 1 if valid, 0 if not.
+ */
+static int tams_normalize_uuid(char *s)
+{
+    if (!tams_is_valid_uuid(s))
+        return 0;
+    for (; *s; s++)
+        *s = av_tolower(*s);
+    return 1;
+}
+
+static void tams_generate_uuid(char out[TAMS_UUID_SIZE])
+{
+    AVUUID uu;
+
+    if (av_random_bytes(uu, sizeof(uu)) < 0) {
+        for (size_t i = 0; i < sizeof(uu); i++)
+            uu[i] = av_get_random_seed() & 0xFF;
+    }
+    uu[6] = (uu[6] & 0x0F) | 0x40; /* version 4 */
+    uu[8] = (uu[8] & 0x3F) | 0x80; /* variant 10 */
+    av_uuid_unparse(uu, out);
+}
+
+static void tams_log_mapping_summary(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    av_log(s, AV_LOG_INFO, "TAMS mapping summary:\n");
+
+    av_log(s, AV_LOG_INFO, "  Containers: %d\n", c->nb_container_ctxs);
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        const TAMSContainerContext *cc = &c->container_ctxs[i];
+
+        av_log(s, AV_LOG_INFO, "    Container[%d]: oformat=%s, owner=%s\n",
+               i, cc->oformat->name, cc->owner_flow_id);
+        for (int j = 0; j < cc->nb_streams; j++) {
+            av_log(s, AV_LOG_INFO, "      stream %d -> ", 
cc->stream_indices[j]);
+            ff_tams_log_flow_summary(s, AV_LOG_INFO, &cc->flow_ctxs[j].flow);
+        }
+    }
+
+    av_log(s, AV_LOG_INFO, "  Multi-Flows: %d\n", c->nb_multi_flow_ctxs);
+    for (int i = 0; i < c->nb_multi_flow_ctxs; i++) {
+        av_log(s, AV_LOG_INFO, "    Multi[%d]: ", i);
+        ff_tams_log_flow_summary(s, AV_LOG_INFO, &c->multi_flow_ctxs[i].flow);
+    }
+}
+
+static void tams_free_container_ctxs(TAMSContainerContext *container_ctxs, int 
nb_container_ctxs)
+{
+    if (!container_ctxs)
+        return;
+    for (int i = 0; i < nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &container_ctxs[i];
+
+        av_freep(&cc->next_put_url);
+        av_freep(&cc->next_object_id);
+        av_freep(&cc->prev.put_url);
+        av_freep(&cc->prev.object_id);
+        av_freep(&cc->passed_cut);
+        if (cc->prev.sub_ctx && cc->prev.sub_ctx->pb) {
+            uint8_t *buf = NULL;
+            avio_close_dyn_buf(cc->prev.sub_ctx->pb, &buf);
+            cc->prev.sub_ctx->pb = NULL;
+            av_free(buf);
+        }
+        avformat_free_context(cc->prev.sub_ctx);
+        av_freep(&cc->stream_indices);
+        av_freep(&cc->flow_ctxs);
+        if (cc->sub_ctx && cc->sub_ctx->pb) {
+            uint8_t *buf = NULL;
+            avio_close_dyn_buf(cc->sub_ctx->pb, &buf);
+            cc->sub_ctx->pb = NULL;
+            av_free(buf);
+        }
+        avformat_free_context(cc->sub_ctx);
+    }
+    av_free(container_ctxs);
+}
+
+static void tams_free_multi_flow_ctxs(TAMSMultiFlowContext *multi_flow_ctxs, 
int nb_multi_flow_ctxs)
+{
+    if (!multi_flow_ctxs)
+        return;
+    for (int i = 0; i < nb_multi_flow_ctxs; i++)
+        av_freep(&multi_flow_ctxs[i].container_indices);
+    av_free(multi_flow_ctxs);
+}
+
+/*
+ * Derive the c->flows_base_url from the provided URL. It must be the store's 
"/flows" collection URL.
+ */
+static int tams_derive_base_url(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int is_exact = 0;
+    int ret = ff_tams_derive_base_url(s->url, c->flows_base_url, 
sizeof(c->flows_base_url),
+                                      &is_exact);
+    if (ret >= 0 && !is_exact)
+        ret = AVERROR(EINVAL);
+    if (ret < 0)
+        av_log(s, AV_LOG_ERROR,
+               "TAMS output URL must be the store's \"/flows\" collection 
endpoint "
+               "(e.g. http://host/flows), got '%s'\n", s->url);
+    return ret;
+}
+
+/*
+ * Derive video/raw flow properties from the pixel format.
+ */
+static int tams_derive_raw_video_params(AVFormatContext *s, int pix_fmt, 
TAMSFlow *flow)
+{
+    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+
+    if (!desc)
+        return AVERROR(EINVAL);
+
+    flow->bit_depth = desc->comp[0].depth;
+    flow->component_type = desc->flags & AV_PIX_FMT_FLAG_RGB ? 
TAMS_COMPONENT_RGB
+                                                              : 
TAMS_COMPONENT_YCBCR;
+    if (!(desc->flags & AV_PIX_FMT_FLAG_RGB) && desc->nb_components >= 3) {
+        flow->horiz_chroma_subs = 1 << desc->log2_chroma_w;
+        flow->vert_chroma_subs  = 1 << desc->log2_chroma_h;
+    }
+
+    if (desc->flags & AV_PIX_FMT_FLAG_PLANAR) {
+        flow->video_unc_type = TAMS_VIDEO_UNC_PLANAR;
+        return 0;
+    }
+    flow->video_unc_type = ff_tams_unc_type_from_pix_fmt(pix_fmt);
+    if (flow->video_unc_type != TAMS_VIDEO_UNC_UNKNOWN)
+        return 0;
+
+    av_log(s, AV_LOG_ERROR, "TAMS: raw pixel format %s has no TAMS 
unc_type\n", desc->name);
+    return AVERROR(EINVAL);
+}
+
+/*
+ * Thin wrapper binding this muxer's captured avio_opts/retry options to the
+ * shared ff_tams_request() helper
+ */
+static int tams_request(AVFormatContext *s, const char *url, const char 
*method,
+                        const uint8_t *body, int body_size, const char 
*content_type,
+                        AVBPrint *out)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    return ff_tams_request(s, &c->avio_opts, url, method, body, body_size, 
content_type,
+                           c->retry_max, c->retry_backoff_us, out);
+}
+
+/*
+ * Return the container_mapping format_track_index of stream k of a container.
+ * A zero-based position among the container's streams of the same media type.
+ */
+static int tams_format_track_index(const AVFormatContext *s, const 
TAMSContainerContext *cc, int k)
+{
+    enum AVMediaType t = 
s->streams[cc->stream_indices[k]]->codecpar->codec_type;
+    int index = 0;
+
+    for (int j = 0; j < k; j++)
+        if (s->streams[cc->stream_indices[j]]->codecpar->codec_type == t)
+            index++;
+    return index;
+}
+
+/*
+ * Copy every AVStream metadata entry other than "title"/"comment" (already
+ * consumed as label/description) into flow as a tag.
+ */
+static int tams_apply_stream_tags(AVFormatContext *s, const AVDictionary 
*metadata, TAMSFlow *flow)
+{
+    const AVDictionaryEntry *t = NULL;
+
+    while ((t = av_dict_iterate(metadata, t))) {
+        if (!strcmp(t->key, "title") || !strcmp(t->key, "comment"))
+            continue;
+        if (flow->nb_tags >= TAMS_MAX_TAGS ||
+            strlen(t->key) >= TAMS_TAG_KEY_SIZE || strlen(t->value) >= 
TAMS_TAG_VALUE_SIZE) {
+            av_log(s, AV_LOG_ERROR, "TAMS: too many stream metadata tags, or 
tag '%s' too long\n", t->key);
+            return AVERROR(EINVAL);
+        }
+        av_strlcpy(flow->tags[flow->nb_tags].key, t->key, 
sizeof(flow->tags[flow->nb_tags].key));
+        av_strlcpy(flow->tags[flow->nb_tags].value, t->value, 
sizeof(flow->tags[flow->nb_tags].value));
+        flow->nb_tags++;
+    }
+
+    return 0;
+}
+
+/**
+ * Append a fresh standalone single-stream TAMSContainerContext for 
stream_index.
+ * Used both when no -flow_map is provided or for any stream -flow_map leaves 
unmentioned.
+ */
+static int tams_append_mono_container(int stream_index,
+                                       TAMSContainerContext 
**container_ctxs_inout,
+                                       int *nb_container_ctxs_inout)
+{
+    TAMSContainerContext *tmp_container_ctxs, *container_ctx;
+
+    tmp_container_ctxs = av_realloc_array(*container_ctxs_inout, 
*nb_container_ctxs_inout + 1,
+                                          sizeof(**container_ctxs_inout));
+    if (!tmp_container_ctxs)
+        return AVERROR(ENOMEM);
+    *container_ctxs_inout = tmp_container_ctxs;
+    container_ctx = &(*container_ctxs_inout)[*nb_container_ctxs_inout];
+    memset(container_ctx, 0, sizeof(*container_ctx));
+
+    container_ctx->stream_indices = av_malloc(sizeof(int));
+    if (!container_ctx->stream_indices)
+        return AVERROR(ENOMEM);
+    container_ctx->stream_indices[0] = stream_index;
+    container_ctx->nb_streams        = 1;
+    container_ctx->multi_flow_index  = -1;
+    container_ctx->has_multi_flow    = 0;
+
+    container_ctx->flow_ctxs = av_calloc(1, sizeof(*container_ctx->flow_ctxs));
+    if (!container_ctx->flow_ctxs) {
+        av_freep(&container_ctx->stream_indices);
+        return AVERROR(ENOMEM);
+    }
+    container_ctx->flow_ctxs[0].stream_index = stream_index;
+
+    (*nb_container_ctxs_inout)++;
+    return 0;
+}
+
+/**
+ * Parse one 'flow=streams=...' token.
+ * The 'flow=' prefix should already be consumed by the caller with p
+ * pointing at 'streams=...'.
+ */
+static int tams_parse_flow_token(const char *p, const char *tok_end, int 
nb_streams,
+                                  uint8_t *assigned,
+                                  TAMSContainerContext **container_ctxs_inout, 
int *nb_container_ctxs_inout)
+{
+    int *indices = NULL, nb_indices = 0;
+    char (*ids)[TAMS_UUID_SIZE] = NULL;
+    int nb_ids = 0;
+    char source_id[TAMS_UUID_SIZE];
+    int has_source_id = 0;
+    int multi_flow_index = -1, has_multi_flow = 0;
+    TAMSContainerContext *tmp_container_ctxs, *container_ctx;
+    int ret;
+
+    source_id[0] = '\0';
+
+    if (strncmp(p, "streams=", 8)) {
+        ret = AVERROR(EINVAL);
+        goto fail;
+    }
+    p += 8;
+
+    /* stream index list */
+    for (;;) {
+        long idx;
+        char *end;
+        int *tmp;
+
+        idx = strtol(p, &end, 10);
+        if (end == p || idx < 0 || idx >= nb_streams) {
+            ret = AVERROR(EINVAL);
+            goto fail;
+        }
+        if (assigned[idx]) {
+            ret = AVERROR(EINVAL); /* duplicate assignment */
+            goto fail;
+        }
+        assigned[idx] = 1;
+
+        tmp = av_realloc_array(indices, nb_indices + 1, sizeof(*indices));
+        if (!tmp) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        indices = tmp;
+        indices[nb_indices++] = (int)idx;
+
+        p = end;
+        if (p >= tok_end || *p != ',')
+            break;
+        p++; /* skip ',' */
+        if (p >= tok_end || !av_isdigit(*p))
+            break; /* next is an attr, not another index; comma already 
consumed */
+    }
+
+    /* attrs: id=, source_id=, multi_flow= (any order, comma-separated) */
+    while (p < tok_end) {
+        if (!strncmp(p, "id=", 3)) {
+            const char *v = p + 3;
+            const char *v_end = memchr(v, ',', tok_end - v);
+            char (*tmp)[TAMS_UUID_SIZE];
+
+            if (!v_end)
+                v_end = tok_end;
+            if (nb_ids >= nb_indices) {
+                ret = AVERROR(EINVAL); /* more ids than streams */
+                goto fail;
+            }
+            if ((size_t)(v_end - v) >= TAMS_UUID_SIZE) {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            tmp = av_realloc_array(ids, nb_ids + 1, sizeof(*ids));
+            if (!tmp) {
+                ret = AVERROR(ENOMEM);
+                goto fail;
+            }
+            ids = tmp;
+            memcpy(ids[nb_ids], v, v_end - v);
+            ids[nb_ids][v_end - v] = '\0';
+            if (!tams_normalize_uuid(ids[nb_ids])) { /* forced to lower case */
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            nb_ids++;
+            p = v_end;
+        } else if (!strncmp(p, "source_id=", 10)) {
+            const char *v = p + 10;
+            const char *v_end = memchr(v, ',', tok_end - v);
+
+            if (!v_end)
+                v_end = tok_end;
+            if (has_source_id) {
+                ret = AVERROR(EINVAL); /* duplicate key */
+                goto fail;
+            }
+            if ((size_t)(v_end - v) >= sizeof(source_id)) {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            memcpy(source_id, v, v_end - v);
+            source_id[v_end - v] = '\0';
+            if (!tams_normalize_uuid(source_id)) { /* forced to lower case */
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            has_source_id = 1;
+            p = v_end;
+        } else if (!strncmp(p, "multi_flow=", 11)) {
+            const char *v = p + 11;
+            long n;
+            char *end;
+
+            if (has_multi_flow) {
+                ret = AVERROR(EINVAL); /* duplicate key */
+                goto fail;
+            }
+            n = strtol(v, &end, 10);
+            if (end == v || n < 0 || (end < tok_end && *end != ',')) {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            multi_flow_index = (int)n;
+            has_multi_flow = 1;
+            p = end;
+        } else {
+            ret = AVERROR(EINVAL); /* unknown attr */
+            goto fail;
+        }
+
+        if (p < tok_end) {
+            if (*p != ',') {
+                ret = AVERROR(EINVAL);
+                goto fail;
+            }
+            p++;
+        }
+    }
+
+    /*
+     * container_mapping (needed whenever >1 stream shares this container)
+     * only has meaning inside a multi-Flow's flow_collection
+     */
+    if (nb_indices > 1 && !has_multi_flow) {
+        ret = AVERROR(EINVAL);
+        goto fail;
+    }
+
+    tmp_container_ctxs = av_realloc_array(*container_ctxs_inout, 
*nb_container_ctxs_inout + 1,
+                                          sizeof(**container_ctxs_inout));
+    if (!tmp_container_ctxs) {
+        ret = AVERROR(ENOMEM);
+        goto fail;
+    }
+    *container_ctxs_inout = tmp_container_ctxs;
+    container_ctx = &(*container_ctxs_inout)[*nb_container_ctxs_inout];
+    memset(container_ctx, 0, sizeof(*container_ctx));
+    container_ctx->stream_indices   = indices; /* ownership transferred */
+    container_ctx->nb_streams       = nb_indices;
+    container_ctx->multi_flow_index = multi_flow_index;
+    container_ctx->has_multi_flow   = has_multi_flow;
+
+    container_ctx->flow_ctxs = av_calloc(nb_indices, 
sizeof(*container_ctx->flow_ctxs));
+    if (!container_ctx->flow_ctxs) {
+        av_freep(&container_ctx->stream_indices);
+        ret = AVERROR(ENOMEM);
+        goto fail_no_indices;
+    }
+    (*nb_container_ctxs_inout)++;
+    for (int i = 0; i < nb_indices; i++) {
+        container_ctx->flow_ctxs[i].stream_index = indices[i];
+        if (i < nb_ids) {
+            av_strlcpy(container_ctx->flow_ctxs[i].flow_id, ids[i],
+                      sizeof(container_ctx->flow_ctxs[i].flow_id));
+            container_ctx->flow_ctxs[i].has_flow_id = 1;
+        }
+        if (has_source_id) {
+            av_strlcpy(container_ctx->flow_ctxs[i].source_id, source_id,
+                      sizeof(container_ctx->flow_ctxs[i].source_id));
+            container_ctx->flow_ctxs[i].has_source_id = 1;
+        }
+    }
+
+    av_free(ids);
+    return 0;
+
+fail:
+    av_free(indices);
+fail_no_indices:
+    av_free(ids);
+    return ret;
+}
+
+/**
+ * Parse one standalone 'multi_flow=N,...' token.
+ * The 'multi_flow=' prefix should already be consumed by the caller with p
+ * pointing at 'N,...'.
+ */
+static int tams_parse_multi_flow_token(const char *p, const char *tok_end,
+                                        TAMSMultiFlowContext 
**multi_flow_ctxs_inout,
+                                        int *nb_multi_flow_ctxs_inout)
+{
+    long n;
+    char *end;
+    char id[TAMS_UUID_SIZE];
+    int has_id = 0;
+    char source_id[TAMS_UUID_SIZE];
+    int has_source_id = 0;
+    char label[256];
+    int has_label = 0;
+    char description[1024];
+    int has_description = 0;
+    TAMSTag tags[TAMS_MAX_TAGS];
+    int nb_tags = 0;
+    TAMSMultiFlowContext *tmp_multi_flow_ctxs, *multi_flow_ctx;
+
+    id[0] = source_id[0] = label[0] = description[0] = '\0';
+
+    n = strtol(p, &end, 10);
+    if (end == p || n < 0 || (end < tok_end && *end != ','))
+        return AVERROR(EINVAL);
+    p = end;
+    if (p >= tok_end || *p != ',')
+        return AVERROR(EINVAL); /* must have at least one attr */
+    p++;
+
+    while (p < tok_end) {
+        if (!strncmp(p, "id=", 3)) {
+            const char *v = p + 3;
+            const char *v_end = memchr(v, ',', tok_end - v);
+
+            if (!v_end)
+                v_end = tok_end;
+            if (has_id || (size_t)(v_end - v) >= sizeof(id))
+                return AVERROR(EINVAL);
+            memcpy(id, v, v_end - v);
+            id[v_end - v] = '\0';
+            if (!tams_normalize_uuid(id)) /* forced to lower case */
+                return AVERROR(EINVAL);
+            has_id = 1;
+            p = v_end;
+        } else if (!strncmp(p, "source_id=", 10)) {
+            const char *v = p + 10;
+            const char *v_end = memchr(v, ',', tok_end - v);
+
+            if (!v_end)
+                v_end = tok_end;
+            if (has_source_id || (size_t)(v_end - v) >= sizeof(source_id))
+                return AVERROR(EINVAL);
+            memcpy(source_id, v, v_end - v);
+            source_id[v_end - v] = '\0';
+            if (!tams_normalize_uuid(source_id)) /* forced to lower case */
+                return AVERROR(EINVAL);
+            has_source_id = 1;
+            p = v_end;
+        } else if (!strncmp(p, "label=", 6)) {
+            const char *v = p + 6;
+            const char *v_end = memchr(v, ',', tok_end - v);
+
+            if (!v_end)
+                v_end = tok_end;
+            if (has_label || (size_t)(v_end - v) >= sizeof(label))
+                return AVERROR(EINVAL);
+            memcpy(label, v, v_end - v);
+            label[v_end - v] = '\0';
+            has_label = 1;
+            p = v_end;
+        } else if (!strncmp(p, "description=", 12)) {
+            const char *v = p + 12;
+            const char *v_end = memchr(v, ',', tok_end - v);
+
+            if (!v_end)
+                v_end = tok_end;
+            if (has_description || (size_t)(v_end - v) >= sizeof(description))
+                return AVERROR(EINVAL);
+            memcpy(description, v, v_end - v);
+            description[v_end - v] = '\0';
+            has_description = 1;
+            p = v_end;
+        } else if (!strncmp(p, "tags.", 5)) {
+            const char *name = p + 5;
+            const char *eq = memchr(name, '=', tok_end - name);
+            const char *v, *v_end;
+            size_t name_len;
+
+            if (!eq)
+                return AVERROR(EINVAL);
+            name_len = eq - name;
+            v = eq + 1;
+            v_end = memchr(v, ',', tok_end - v);
+            if (!v_end)
+                v_end = tok_end;
+            if (nb_tags >= TAMS_MAX_TAGS ||
+                name_len >= TAMS_TAG_KEY_SIZE || (size_t)(v_end - v) >= 
TAMS_TAG_VALUE_SIZE)
+                return AVERROR(EINVAL);
+            memcpy(tags[nb_tags].key, name, name_len);
+            tags[nb_tags].key[name_len] = '\0';
+            memcpy(tags[nb_tags].value, v, v_end - v);
+            tags[nb_tags].value[v_end - v] = '\0';
+            nb_tags++;
+            p = v_end;
+        } else {
+            return AVERROR(EINVAL); /* unknown attr */
+        }
+
+        if (p < tok_end) {
+            if (*p != ',')
+                return AVERROR(EINVAL);
+            p++;
+        }
+    }
+
+    for (int i = 0; i < *nb_multi_flow_ctxs_inout; i++) {
+        if ((*multi_flow_ctxs_inout)[i].index == (int)n)
+            return AVERROR(EINVAL); /* duplicate multi_flow index */
+    }
+
+    tmp_multi_flow_ctxs = av_realloc_array(*multi_flow_ctxs_inout, 
*nb_multi_flow_ctxs_inout + 1,
+                                           sizeof(**multi_flow_ctxs_inout));
+    if (!tmp_multi_flow_ctxs)
+        return AVERROR(ENOMEM);
+    *multi_flow_ctxs_inout = tmp_multi_flow_ctxs;
+    multi_flow_ctx = &(*multi_flow_ctxs_inout)[(*nb_multi_flow_ctxs_inout)++];
+    memset(multi_flow_ctx, 0, sizeof(*multi_flow_ctx));
+    multi_flow_ctx->index = (int)n;
+    if (has_id) {
+        av_strlcpy(multi_flow_ctx->flow_id, id, 
sizeof(multi_flow_ctx->flow_id));
+        multi_flow_ctx->has_flow_id = 1;
+    }
+    if (has_source_id) {
+        av_strlcpy(multi_flow_ctx->source_id, source_id, 
sizeof(multi_flow_ctx->source_id));
+        multi_flow_ctx->has_source_id = 1;
+    }
+    if (has_label)
+        av_strlcpy(multi_flow_ctx->label, label, 
sizeof(multi_flow_ctx->label));
+    if (has_description)
+        av_strlcpy(multi_flow_ctx->description, description, 
sizeof(multi_flow_ctx->description));
+    if (nb_tags) {
+        memcpy(multi_flow_ctx->tags, tags, nb_tags * sizeof(*tags));
+        multi_flow_ctx->nb_tags = nb_tags;
+    }
+
+    return 0;
+}
+
+/*
+ * Grammar (see doc/muxers.texi for worked examples):
+ *
+ *   flow_map         := token (' ' token)*
+ *   token            := flow_token | multi_flow_token
+ *
+ *   flow_token       := 'flow=streams=' index (',' index)* (',' flow_attr)*
+ *   flow_attr        := 'id=' uuid | 'source_id=' uuid | 'multi_flow=' integer
+ *
+ *   multi_flow_token := 'multi_flow=' integer ',' multi_attr (',' multi_attr)*
+ *   multi_attr       := 'id=' uuid | 'source_id=' uuid | 'label=' text |
+ *                        'description=' text | 'tags.' name '=' text
+ *
+ * An AVStream index may appear in at most one flow_token. It is not required
+ * to appear in any. Any stream index the -flow_map doesn't mention defaults
+ * to its own standalone mono Flow. The same behaviour occurs when -flow_map
+ * is omitted entirely.
+ *
+ * id= may repeat within one flow_token, positionally paired with the streams= 
list.
+ *
+ * A source_id=/multi_flow= may each appear at most once per flow_token.
+ *
+ * A flow_token with more than one stream requires a multi_flow= attr, as a
+ * shared container is only possible within a multi-Flow. A multi_flow_token
+ * for that N is optional: it is only needed to set the multi-Flow's
+ * id=/source_id=/label=/description=/tags.
+ *
+ * label=/description=/tags.<name>= are not supported on a flow_token,
+ * as a mono Flow's label/description come from that AVStream's 
"title"/"comment"
+ * metadata instead, and its tags from any other AVStream metadata key.
+ *
+ * A multi_flow_token with id= is considered pinned and never modified
+ * so label=/description=/tags.<name>= are ignored.
+ *
+ * tags.<name>= may repeat.
+ *
+ * Because ',' and ' ' are the token/attr delimiters, text values may contain 
neither.
+ */
+static int tams_parse_flow_map(const char *str, int nb_streams,
+                                TAMSContainerContext **container_ctxs_out, int 
*nb_container_ctxs_out,
+                                TAMSMultiFlowContext **multi_flow_ctxs_out, 
int *nb_multi_flow_ctxs_out)
+{
+    TAMSContainerContext *container_ctxs = NULL;
+    int nb_container_ctxs = 0;
+    TAMSMultiFlowContext *multi_flow_ctxs = NULL;
+    int nb_multi_flow_ctxs = 0;
+    uint8_t *assigned = NULL;
+    const char *p;
+    int ret;
+
+    *container_ctxs_out    = NULL;
+    *nb_container_ctxs_out = 0;
+    *multi_flow_ctxs_out    = NULL;
+    *nb_multi_flow_ctxs_out = 0;
+
+    if (nb_streams <= 0)
+        return AVERROR(EINVAL);
+
+    if (!str || !str[0]) {
+        for (int i = 0; i < nb_streams; i++) {
+            ret = tams_append_mono_container(i, &container_ctxs, 
&nb_container_ctxs);
+            if (ret < 0) {
+                tams_free_container_ctxs(container_ctxs, nb_container_ctxs);
+                return ret;
+            }
+        }
+        *container_ctxs_out    = container_ctxs;
+        *nb_container_ctxs_out = nb_container_ctxs;
+        return 0;
+    }
+
+    assigned = av_calloc(nb_streams, sizeof(*assigned));
+    if (!assigned)
+        return AVERROR(ENOMEM);
+
+    p = str;
+    while (*p) {
+        const char *tok_end;
+
+        while (*p == ' ')
+            p++;
+        if (!*p)
+            break;
+
+        tok_end = strchr(p, ' ');
+        if (!tok_end)
+            tok_end = p + strlen(p);
+
+        if (!strncmp(p, "flow=", 5)) {
+            ret = tams_parse_flow_token(p + 5, tok_end, nb_streams, assigned,
+                                        &container_ctxs, &nb_container_ctxs);
+        } else if (!strncmp(p, "multi_flow=", 11)) {
+            ret = tams_parse_multi_flow_token(p + 11, tok_end, 
&multi_flow_ctxs, &nb_multi_flow_ctxs);
+        } else {
+            ret = AVERROR(EINVAL); /* unknown token */
+        }
+        if (ret < 0)
+            goto fail;
+
+        p = tok_end;
+    }
+
+    /*
+     * Any stream not explicitly mentioned in a flow= token defaults to its
+     * own standalone mono Flow, same as when -flow_map is omitted entirely
+     */
+    for (int i = 0; i < nb_streams; i++) {
+        if (assigned[i])
+            continue;
+        ret = tams_append_mono_container(i, &container_ctxs, 
&nb_container_ctxs);
+        if (ret < 0)
+            goto fail;
+        assigned[i] = 1;
+    }
+
+    /*
+     * Create a TAMSMultiFlowContext for any multi_flow_index
+     * referenced by a container that has no standalone 'multi_flow=N,...'
+     * token of its own e.g. a brand-new multi with no id=/source_id= to set
+     */
+    for (int j = 0; j < nb_container_ctxs; j++) {
+        TAMSMultiFlowContext *tmp_multi_flow_ctxs;
+        int found = 0;
+
+        if (!container_ctxs[j].has_multi_flow)
+            continue;
+        for (int i = 0; i < nb_multi_flow_ctxs; i++) {
+            if (multi_flow_ctxs[i].index == 
container_ctxs[j].multi_flow_index) {
+                found = 1;
+                break;
+            }
+        }
+        if (found)
+            continue;
+
+        tmp_multi_flow_ctxs = av_realloc_array(multi_flow_ctxs, 
nb_multi_flow_ctxs + 1,
+                                               sizeof(*multi_flow_ctxs));
+        if (!tmp_multi_flow_ctxs) {
+            ret = AVERROR(ENOMEM);
+            goto fail;
+        }
+        multi_flow_ctxs = tmp_multi_flow_ctxs;
+        memset(&multi_flow_ctxs[nb_multi_flow_ctxs], 0, 
sizeof(*multi_flow_ctxs));
+        multi_flow_ctxs[nb_multi_flow_ctxs].index = 
container_ctxs[j].multi_flow_index;
+        nb_multi_flow_ctxs++;
+    }
+
+    /*
+     * Cross-link each multi-flow to its member containers. Error on orphan
+     * multi_flow= tokens (index never referenced by any flow= token)
+     */
+    for (int i = 0; i < nb_multi_flow_ctxs; i++) {
+        int *gidx = NULL, ngidx = 0;
+
+        for (int j = 0; j < nb_container_ctxs; j++) {
+            if (container_ctxs[j].has_multi_flow &&
+                container_ctxs[j].multi_flow_index == 
multi_flow_ctxs[i].index) {
+                int *tmp = av_realloc_array(gidx, ngidx + 1, sizeof(*gidx));
+                if (!tmp) {
+                    av_free(gidx);
+                    ret = AVERROR(ENOMEM);
+                    goto fail;
+                }
+                gidx = tmp;
+                gidx[ngidx++] = j;
+            }
+        }
+        if (ngidx == 0) {
+            av_free(gidx);
+            ret = AVERROR(EINVAL); /* orphan multi_flow= token */
+            goto fail;
+        }
+        multi_flow_ctxs[i].container_indices    = gidx;
+        multi_flow_ctxs[i].nb_container_indices = ngidx;
+    }
+
+    av_free(assigned);
+    *container_ctxs_out    = container_ctxs;
+    *nb_container_ctxs_out = nb_container_ctxs;
+    *multi_flow_ctxs_out    = multi_flow_ctxs;
+    *nb_multi_flow_ctxs_out = nb_multi_flow_ctxs;
+    return 0;
+
+fail:
+    av_free(assigned);
+    tams_free_container_ctxs(container_ctxs, nb_container_ctxs);
+    tams_free_multi_flow_ctxs(multi_flow_ctxs, nb_multi_flow_ctxs);
+    return ret;
+}
+
+static int tams_validate_stream(AVFormatContext *s, const AVStream *st)
+{
+    const AVCodecParameters *par = st->codecpar;
+
+    if (!ff_tams_mime_from_codec(par->codec_id)) {
+        av_log(s, AV_LOG_ERROR, "TAMS: codec %s has no known TAMS codec MIME 
mapping\n",
+               avcodec_get_name(par->codec_id));
+        return AVERROR(EINVAL);
+    }
+
+    switch (par->codec_type) {
+    case AVMEDIA_TYPE_VIDEO:
+        if (par->width <= 0 || par->height <= 0) {
+            av_log(s, AV_LOG_ERROR, "TAMS: video stream missing frame 
dimensions\n");
+            return AVERROR(EINVAL);
+        }
+        break;
+    case AVMEDIA_TYPE_AUDIO:
+        if (par->sample_rate <= 0 || par->ch_layout.nb_channels <= 0) {
+            av_log(s, AV_LOG_ERROR, "TAMS: audio stream missing sample_rate or 
channels\n");
+            return AVERROR(EINVAL);
+        }
+        break;
+    case AVMEDIA_TYPE_SUBTITLE:
+        break;
+    default:
+        av_log(s, AV_LOG_ERROR, "TAMS: unsupported media type for stream 
%d\n", st->index);
+        return AVERROR(EINVAL);
+    }
+
+    return 0;
+}
+
+static int tams_validate_streams(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        int ret;
+
+        for (int j = 0; j < cc->nb_streams; j++) {
+            ret = tams_validate_stream(s, s->streams[cc->stream_indices[j]]);
+            if (ret < 0)
+                return ret;
+        }
+    }
+
+    return 0;
+}
+
+static int tams_validate_pinned_flow(AVFormatContext *s, const AVStream *ist, 
const TAMSFlow *flow)
+{
+    const AVCodecParameters *par = ist->codecpar;
+
+    if (flow->codec[0]) {
+        const char *mime = ff_tams_mime_from_codec(par->codec_id);
+        if (mime && av_strcasecmp(mime, flow->codec)) {
+            av_log(s, AV_LOG_ERROR, "TAMS: pinned Flow %s codec %s != stream 
codec %s\n",
+                   flow->id, flow->codec, mime);
+            return AVERROR(EINVAL);
+        }
+    }
+    if (flow->format == TAMS_FORMAT_VIDEO) {
+        if (flow->frame_width != par->width || flow->frame_height != 
par->height) {
+            av_log(s, AV_LOG_ERROR, "TAMS: pinned Flow %s dimensions %dx%d != 
stream %dx%d\n",
+                   flow->id, flow->frame_width, flow->frame_height, 
par->width, par->height);
+            return AVERROR(EINVAL);
+        }
+    } else if (flow->format == TAMS_FORMAT_AUDIO) {
+        if (flow->sample_rate != par->sample_rate || flow->channels != 
par->ch_layout.nb_channels) {
+            av_log(s, AV_LOG_ERROR, "TAMS: pinned Flow %s sample_rate/channels 
%d/%d != stream %d/%d\n",
+                   flow->id, flow->sample_rate, flow->channels,
+                   par->sample_rate, par->ch_layout.nb_channels);
+            return AVERROR(EINVAL);
+        }
+    }
+
+    return 0;
+}
+
+/* GET /service. Warn on an api_version mismatch and store the timeouts. */
+static int tams_fetch_service_limits(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    char url[2100];
+    AVBPrint buf;
+    TAMSService service;
+    int ret;
+
+    ret = ff_tams_service_url(c->flows_base_url, url, sizeof(url));
+    if (ret < 0)
+        return ret;
+
+    ret = tams_request(s, url, NULL, NULL, 0, NULL, &buf);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: GET /service failed: %s\n", 
av_err2str(ret));
+        return ret;
+    }
+
+    ret = ff_tams_service_from_json(buf.str, &service);
+    av_bprint_finalize(&buf, NULL);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: malformed /service response\n");
+        return ret;
+    }
+
+    if (service.api_version[0] && strcmp(service.api_version, 
TAMS_API_VERSION))
+        av_log(s, AV_LOG_WARNING,
+               "TAMS service api_version '%s' does not match the version this "
+               "muxer was written against ('%s'); continuing anyway\n",
+               service.api_version, TAMS_API_VERSION);
+
+    c->min_object_timeout_us = service.min_object_timeout > 0
+                              ? service.min_object_timeout * INT64_C(1000000) 
: 300 * INT64_C(1000000);
+    c->min_presigned_url_timeout_us = service.min_presigned_url_timeout > 0
+                                     ? service.min_presigned_url_timeout * 
INT64_C(1000000) : 30 * INT64_C(1000000);
+
+    return 0;
+}
+
+/*
+ * Hard-error if any container's segment duration is longer than the store's
+ * minimum presigned URL timeout.
+ */
+static int tams_check_segment_durations(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        int64_t dur_us = c->container_ctxs[i].segment_duration_ns / 1000;
+        if (dur_us > 0 && dur_us >= c->min_presigned_url_timeout_us) {
+            av_log(s, AV_LOG_ERROR,
+                   "TAMS: segment duration (%"PRId64" us) may exceed the 
store's "
+                   "min_presigned_url_timeout (%"PRId64" us); the 
eagerly-allocated "
+                   "put_url for a segment could expire before it is 
uploaded\n",
+                   dur_us, c->min_presigned_url_timeout_us);
+            return AVERROR(EINVAL);
+        }
+    }
+
+    return 0;
+}
+
+static int tams_fetch_flow(AVFormatContext *s, const char *flow_id, TAMSFlow 
*out)
+{
+    TAMSMuxContext *c = s->priv_data;
+    char url[2100];
+    AVBPrint buf;
+    TAMSFlow *flows = NULL;
+    int nb_flows = 0;
+    int ret;
+
+    ret = ff_tams_flow_url(c->flows_base_url, flow_id, url, sizeof(url));
+    if (ret < 0)
+        return ret;
+
+    ret = tams_request(s, url, NULL, NULL, 0, NULL, &buf);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: failed to GET pinned Flow %s: %s\n",
+               flow_id, av_err2str(ret));
+        return ret;
+    }
+
+    ret = ff_tams_flows_from_json(buf.str, &flows, &nb_flows);
+    av_bprint_finalize(&buf, NULL);
+    if (ret < 0 || nb_flows != 1) {
+        av_freep(&flows);
+        av_log(s, AV_LOG_ERROR, "TAMS: malformed response for pinned Flow 
%s\n", flow_id);
+        return ret < 0 ? ret : AVERROR_INVALIDDATA;
+    }
+
+    *out = flows[0];
+    av_free(flows);
+    return 0;
+}
+
+/* PUT /flows/{id} to create a new Flow. */
+static int tams_create_flow(AVFormatContext *s, TAMSFlow *flow)
+{
+    TAMSMuxContext *c = s->priv_data;
+    char url[2100];
+    AVBPrint json;
+    int ret;
+
+    ret = ff_tams_flow_url(c->flows_base_url, flow->id, url, sizeof(url));
+    if (ret < 0)
+        return ret;
+
+    av_bprint_init(&json, 0, INT_MAX);
+    ret = ff_tams_flow_to_json(&json, flow);
+    if (ret < 0) {
+        av_bprint_finalize(&json, NULL);
+        return ret;
+    }
+
+    ret = tams_request(s, url, "PUT", (const uint8_t *)json.str, json.len, 
"application/json", NULL);
+    av_bprint_finalize(&json, NULL);
+    if (ret < 0)
+        av_log(s, AV_LOG_ERROR, "TAMS: failed to PUT Flow %s: %s\n", flow->id, 
av_err2str(ret));
+
+    return ret;
+}
+
+/*
+ * Create every multi-Flow which -flow_map did not pin to an id=. Its 
flow_collection
+ * lists each member container's resolved mono Flows.
+ */
+static int tams_create_multi_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_multi_flow_ctxs; i++) {
+        TAMSMultiFlowContext *mc = &c->multi_flow_ctxs[i];
+        int ret;
+
+        /*
+         * Pinned multi-Flows were already fetched and member-matched in
+         * tams_match_pinned_multi_flows().
+         */
+        if (mc->has_flow_id)
+            continue;
+
+        memset(&mc->flow, 0, sizeof(mc->flow));
+        mc->flow.format = TAMS_FORMAT_MULTI;
+        mc->flow.generation = 1;
+
+        tams_generate_uuid(mc->flow_id);
+        mc->has_flow_id = 1;
+        av_strlcpy(mc->flow.id, mc->flow_id, sizeof(mc->flow.id));
+
+        if (mc->has_source_id)
+            av_strlcpy(mc->flow.source_id, mc->source_id, 
sizeof(mc->flow.source_id));
+        else
+            tams_generate_uuid(mc->flow.source_id);
+
+        av_strlcpy(mc->flow.label, mc->label, sizeof(mc->flow.label));
+        av_strlcpy(mc->flow.description, mc->description, 
sizeof(mc->flow.description));
+        memcpy(mc->flow.tags, mc->tags, mc->nb_tags * sizeof(*mc->tags));
+        mc->flow.nb_tags = mc->nb_tags;
+
+        for (int j = 0; j < mc->nb_container_indices; j++) {
+            TAMSContainerContext *cc = 
&c->container_ctxs[mc->container_indices[j]];
+            int shared_container = cc->nb_streams > 1;
+
+            /*
+             * A shared container's bytes belong to the multi-Flow itself,
+             * not to any one member so carry its MIME on the multi Flow.
+             */
+            if (shared_container && !mc->flow.container[0])
+                av_strlcpy(mc->flow.container, cc->container_mime, 
sizeof(mc->flow.container));
+
+            for (int k = 0; k < cc->nb_streams; k++) {
+                TAMSFlowCollectionItem *item;
+                enum AVMediaType t;
+
+                if (mc->flow.nb_flow_collection_items >= 
TAMS_MAX_COLLECTION_ITEMS) {
+                    av_log(s, AV_LOG_ERROR, "TAMS: multi_flow=%d has too many 
member streams\n",
+                           mc->index);
+                    return AVERROR(EINVAL);
+                }
+                item = 
&mc->flow.flow_collection_items[mc->flow.nb_flow_collection_items++];
+                av_strlcpy(item->id, cc->flow_ctxs[k].flow_id, 
sizeof(item->id));
+
+                t = s->streams[cc->stream_indices[k]]->codecpar->codec_type;
+                av_strlcpy(item->role, t == AVMEDIA_TYPE_VIDEO ? "video" :
+                                      t == AVMEDIA_TYPE_AUDIO ? "audio" : 
"data",
+                          sizeof(item->role));
+
+                /*
+                 * container_mapping only has meaning for a shared container.
+                 * It identifies which track within it this Flow occupies
+                 */
+                if (shared_container) {
+                    item->has_container_mapping = 1;
+                    item->container_mapping.track_index = k;
+                    item->container_mapping.has_track_index = 1;
+                    item->container_mapping.format_track_index = 
tams_format_track_index(s, cc, k);
+                    item->container_mapping.has_format_track_index = 1;
+                    if (!strcmp(cc->oformat->name, "mp4")) {
+                        item->container_mapping.isobmff_track_id = k + 1;
+                        item->container_mapping.has_isobmff_track_id = 1;
+                    }
+                }
+            }
+        }
+
+        av_strlcpy(mc->flow.status, "awaiting_content", 
sizeof(mc->flow.status));
+        ret = tams_create_flow(s, &mc->flow);
+        if (ret < 0)
+            return ret;
+        mc->created = 1;
+    }
+
+    return 0;
+}
+
+static int tams_build_container_mux(AVFormatContext *s, TAMSContainerContext 
*cc)
+{
+    AVFormatContext *oc;
+    int ret;
+
+    ret = avformat_alloc_output_context2(&cc->sub_ctx, cc->oformat, NULL, 
NULL);
+    if (ret < 0)
+        return ret;
+    oc = cc->sub_ctx;
+
+    oc->interrupt_callback = s->interrupt_callback;
+    oc->max_delay          = s->max_delay;
+    oc->opaque             = s->opaque;
+    oc->io_close2          = s->io_close2;
+    oc->io_open            = s->io_open;
+    oc->flags              = s->flags;
+
+    /* PTS are Flow times so no mux delay is added */
+    if (!strcmp(cc->oformat->name, "mpegts")) {
+        ret = av_opt_set_int(oc->priv_data, "mpegts_copyts", 1, 0);
+        if (ret < 0)
+            return ret;
+    }
+
+    for (int i = 0; i < cc->nb_streams; i++) {
+        AVStream *ist = s->streams[cc->stream_indices[i]];
+        AVCodecParameters *ipar = ist->codecpar, *opar;
+        AVStream *ost = ff_stream_clone(oc, ist);
+
+        if (!ost)
+            return AVERROR(ENOMEM);
+
+        opar = ost->codecpar;
+        if (!oc->oformat->codec_tag ||
+            av_codec_get_id (oc->oformat->codec_tag, ipar->codec_tag) == 
opar->codec_id ||
+            av_codec_get_tag(oc->oformat->codec_tag, ipar->codec_id) <= 0) {
+            opar->codec_tag = ipar->codec_tag;
+        } else {
+            opar->codec_tag = 0;
+        }
+
+        /*
+         * Make every raw elementary-stream H.264/HEVC/MPEG-2 segment 
decodable on its own.
+         *
+         * The tams muxer advertises AVFMT_GLOBALHEADER and the nested 
containers
+         * need to write the parameter sets into their own headers.
+         *
+         * A decoder needs the codec's parameter sets before the first frame.
+         * An encoder asked for a global header writes the parameter
+         * sets only into extradata, not into the packets.
+         *
+         * A raw elementary-stream segment has no header.
+         * Without the parameter sets in the packets, only a reader
+         * starting from the first segment could decode the stream.
+         *
+         * When the extradata is Annex B (it starts with a 00 00 01 or
+         * 00 00 00 01 start code) use dump_extra=freq=keyframe to prepend it
+         * to every keyframe packet. Each segment starts on a keyframe,
+         * so each one will start with its parameter sets. MPEG-2 has no
+         * avcC-like form: its extradata is always start-code delimited, so
+         * it always takes this path.
+         *
+         * Otherwise if the extradata is avcC/hvcC, e.g. from a stream copy of
+         * MP4/MOV it is left alone. The raw h264/hevc muxer adds
+         * h264_mp4toannexb/hevc_mp4toannexb itself, which converts the
+         * packets to Annex B and inserts the parameter sets before each IDR.
+         */
+        if (opar->extradata_size >= 4 &&
+            // Annex B starts with a 00 00 01 or 00 00 00 01
+            (AV_RB24(opar->extradata) == 1 || AV_RB32(opar->extradata) == 1) &&
+            (!strcmp(oc->oformat->name, "h264") || !strcmp(oc->oformat->name, 
"hevc") ||
+             !strcmp(oc->oformat->name, "mpeg2video"))) {
+            ret = ff_stream_add_bitstream_filter(ost, "dump_extra", 
"freq=keyframe");
+            if (ret < 0)
+                return ret;
+        }
+    }
+
+    return 0;
+}
+
+static int tams_build_containers(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        int ret = tams_resolve_oformat(s, cc);
+
+        if (ret < 0)
+            return ret;
+
+        ret = tams_build_container_mux(s, cc);
+        if (ret < 0)
+            return ret;
+    }
+
+    return 0;
+}
+
+static int tams_build_stream_maps(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    c->stream_to_container = av_malloc_array(s->nb_streams, 
sizeof(*c->stream_to_container));
+    c->stream_to_subindex  = av_malloc_array(s->nb_streams, 
sizeof(*c->stream_to_subindex));
+    if (!c->stream_to_container || !c->stream_to_subindex)
+        return AVERROR(ENOMEM);
+
+    for (int i = 0; i < s->nb_streams; i++) {
+        c->stream_to_container[i] = -1;
+        c->stream_to_subindex[i]  = -1;
+    }
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        for (int j = 0; j < cc->nb_streams; j++) {
+            c->stream_to_container[cc->stream_indices[j]] = i;
+            c->stream_to_subindex[cc->stream_indices[j]]  = j;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Resolve label/description for one mono Flow from that AVStream's own
+ * "title"/"comment" metadata.
+ */
+static void tams_resolve_stream_metadata(const AVStream *st,
+                                         char *label, size_t label_size,
+                                         char *desc, size_t desc_size)
+{
+    AVDictionaryEntry *t;
+
+    t = av_dict_get(st->metadata, "title", NULL, 0);
+    av_strlcpy(label, t ? t->value : "", label_size);
+
+    t = av_dict_get(st->metadata, "comment", NULL, 0);
+    av_strlcpy(desc, t ? t->value : "", desc_size);
+}
+
+/*
+ * Build a fresh TAMSFlow from a mapped AVStream's codec parameters.
+ */
+static int tams_build_flow(AVFormatContext *s, const AVStream *ist,
+                                 const char *container_mime, int 
shared_container,
+                                 TAMSFlow *flow)
+{
+    const AVCodecParameters *par = ist->codecpar;
+    const char *mime;
+    int ret;
+
+    memset(flow, 0, sizeof(*flow));
+
+    switch (par->codec_type) {
+    case AVMEDIA_TYPE_VIDEO:
+        flow->format       = TAMS_FORMAT_VIDEO;
+        flow->frame_width  = par->width;
+        flow->frame_height = par->height;
+        if (ist->avg_frame_rate.num > 0 && ist->avg_frame_rate.den > 0)
+            flow->frame_rate = ist->avg_frame_rate;
+        if (par->bits_per_raw_sample > 0)
+            flow->bit_depth = par->bits_per_raw_sample;
+        if (par->codec_id == AV_CODEC_ID_RAWVIDEO) {
+            ret = tams_derive_raw_video_params(s, par->format, flow);
+            if (ret < 0)
+                return ret;
+        }
+        break;
+    case AVMEDIA_TYPE_AUDIO:
+        flow->format       = TAMS_FORMAT_AUDIO;
+        flow->sample_rate  = par->sample_rate;
+        flow->channels     = par->ch_layout.nb_channels;
+        if (par->bits_per_raw_sample > 0)
+            flow->bit_depth = par->bits_per_raw_sample;
+        else if (av_get_bits_per_sample(par->codec_id) > 0)
+            flow->bit_depth = av_get_bits_per_sample(par->codec_id);
+        if (par->frame_size > 0)
+            flow->coded_frame_size = par->frame_size;
+        break;
+    case AVMEDIA_TYPE_SUBTITLE:
+        flow->format = TAMS_FORMAT_DATA;
+        av_strlcpy(flow->data_type, "text", sizeof(flow->data_type));
+        break;
+    default:
+        return AVERROR(EINVAL);
+    }
+
+    mime = ff_tams_mime_from_codec(par->codec_id);
+    if (!mime)
+        return AVERROR(EINVAL);
+    av_strlcpy(flow->codec, mime, sizeof(flow->codec));
+    /* The mapped PCM codecs are interleaved */
+    if (av_strstart(mime, "audio/x-raw-", NULL))
+        flow->audio_unc_type = TAMS_AUDIO_UNC_INTERLEAVED;
+    if (!shared_container)
+        av_strlcpy(flow->container, container_mime, sizeof(flow->container));
+    flow->generation = 1;
+
+    tams_resolve_stream_metadata(ist, flow->label, sizeof(flow->label),
+                                 flow->description, sizeof(flow->description));
+
+    ret = tams_apply_stream_tags(s, ist->metadata, flow);
+    if (ret < 0)
+        return ret;
+
+    return 0;
+}
+
+static int tams_resolve_container_mime(const AVFormatContext *s, const 
TAMSContainerContext *cc,
+                                       char *out, size_t out_size)
+{
+    for (int i = 0; i < FF_ARRAY_ELEMS(tams_container_mimes); i++) {
+        if (!strcmp(cc->oformat->name, tams_container_mimes[i].muxer_name)) {
+            av_strlcpy(out, tams_container_mimes[i].mime, out_size);
+            return 0;
+        }
+    }
+
+    if (!strcmp(cc->oformat->name, "mp4")) {
+        enum AVMediaType dominant = AVMEDIA_TYPE_DATA;
+
+        for (int j = 0; j < cc->nb_streams; j++) {
+            enum AVMediaType t = 
s->streams[cc->stream_indices[j]]->codecpar->codec_type;
+            if (t == AVMEDIA_TYPE_VIDEO) { dominant = t; break; }
+            if (t == AVMEDIA_TYPE_AUDIO && dominant != AVMEDIA_TYPE_VIDEO) 
dominant = t;
+        }
+        av_strlcpy(out, dominant == AVMEDIA_TYPE_VIDEO ? "video/mp4" :
+                        dominant == AVMEDIA_TYPE_AUDIO ? "audio/mp4" : 
"application/mp4",
+                  out_size);
+        return 0;
+    }
+
+    if (cc->nb_streams == 1) {
+        const char *mime = 
ff_tams_mime_from_codec(s->streams[cc->stream_indices[0]]->codecpar->codec_id);
+        if (mime) {
+            av_strlcpy(out, mime, out_size);
+            return 0;
+        }
+    }
+
+    return AVERROR(EINVAL);
+}
+
+/*
+ * Resolve each container's target segment duration in nanoseconds.
+ * Use -segment_duration if given, else a pinned flow's own segment_duration,
+ * else the 2-second default for newly-created flows.
+ */
+static void tams_resolve_segment_duration(AVFormatContext *s, 
TAMSContainerContext *cc)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    if (c->segment_duration_s >= 0) {
+        cc->segment_duration_ns = c->segment_duration_s * TAMS_TIMEBASE;
+        return;
+    }
+    for (int i = 0; i < cc->nb_streams; i++) {
+        const TAMSFlow *flow = &cc->flow_ctxs[i].flow;
+        if (flow->segment_duration.num > 0 && flow->segment_duration.den > 0) {
+            cc->segment_duration_ns = av_rescale(flow->segment_duration.num, 
TAMS_TIMEBASE,
+                                                 flow->segment_duration.den);
+            return;
+        }
+    }
+    cc->segment_duration_ns = 2 * TAMS_TIMEBASE;
+}
+
+/*
+ * GET and validate every mono Flow -flow_map pinned with an id= and resolve 
each
+ * container's MIME type and segment duration.
+ */
+static int tams_check_mono_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        int ret;
+
+        ret = tams_resolve_container_mime(s, cc, cc->container_mime, 
sizeof(cc->container_mime));
+        if (ret < 0) {
+            av_log(s, AV_LOG_ERROR, "TAMS: could not determine a container 
MIME type\n");
+            return ret;
+        }
+
+        for (int j = 0; j < cc->nb_streams; j++) {
+            TAMSFlowContext *fc = &cc->flow_ctxs[j];
+            AVStream *ist = s->streams[cc->stream_indices[j]];
+
+            if (!fc->has_flow_id)
+                continue;
+            ret = tams_fetch_flow(s, fc->flow_id, &fc->flow);
+            if (ret < 0)
+                return ret;
+            ret = tams_validate_pinned_flow(s, ist, &fc->flow);
+            if (ret < 0)
+                return ret;
+            if (fc->has_source_id && strcmp(fc->flow.source_id, 
fc->source_id)) {
+                av_log(s, AV_LOG_ERROR,
+                       "TAMS: pinned Flow %s source_id %s != -flow_map 
source_id %s\n",
+                       fc->flow_id, fc->flow.source_id, fc->source_id);
+                return AVERROR(EINVAL);
+            }
+        }
+
+        tams_resolve_segment_duration(s, cc);
+    }
+
+    return 0;
+}
+
+/* Build and PUT a new mono Flow for every stream -flow_map did not pin. */
+static int tams_create_mono_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        int shared_container = cc->nb_streams > 1;
+
+        for (int j = 0; j < cc->nb_streams; j++) {
+            TAMSFlowContext *fc = &cc->flow_ctxs[j];
+            AVStream *ist = s->streams[cc->stream_indices[j]];
+            int ret;
+
+            if (fc->has_flow_id)
+                continue;
+
+            ret = tams_build_flow(s, ist, cc->container_mime, 
shared_container, &fc->flow);
+            if (ret < 0)
+                return ret;
+
+            tams_generate_uuid(fc->flow_id);
+            fc->has_flow_id = 1;
+            av_strlcpy(fc->flow.id, fc->flow_id, sizeof(fc->flow.id));
+
+            if (fc->has_source_id)
+                av_strlcpy(fc->flow.source_id, fc->source_id, 
sizeof(fc->flow.source_id));
+            else
+                tams_generate_uuid(fc->flow.source_id);
+
+            av_strlcpy(fc->flow.status, "awaiting_content", 
sizeof(fc->flow.status));
+            ret = tams_create_flow(s, &fc->flow);
+            if (ret < 0)
+                return ret;
+            fc->created = 1;
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * Set the status of the Flows this muxer created (pinned Flows are left
+ * alone) skipping any already at that status. Flows are created
+ * "awaiting_content", set to "ingesting" once their container's first segment
+ * is registered and set to "closed_complete" once the trailer is written.
+ *
+ * If only is NULL, every created Flow is updated. Otherwise only the Flows
+ * written to that specified container are as well as any multi-Flow it 
belongs to.
+ */
+static int tams_set_created_flow_status(AVFormatContext *s, const 
TAMSContainerContext *only,
+                                        const char *status)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int ret = 0;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        if (only && cc != only)
+            continue;
+        for (int j = 0; j < cc->nb_streams; j++) {
+            TAMSFlowContext *fc = &cc->flow_ctxs[j];
+            if (!fc->created || !strcmp(fc->flow.status, status))
+                continue;
+            av_strlcpy(fc->flow.status, status, sizeof(fc->flow.status));
+            ret = tams_create_flow(s, &fc->flow);
+            if (ret < 0)
+                return ret;
+        }
+    }
+    for (int i = 0; i < c->nb_multi_flow_ctxs; i++) {
+        TAMSMultiFlowContext *mc = &c->multi_flow_ctxs[i];
+        if (!mc->created || !strcmp(mc->flow.status, status) ||
+            (only && (!only->has_multi_flow || only->multi_flow_index != 
mc->index)))
+            continue;
+        av_strlcpy(mc->flow.status, status, sizeof(mc->flow.status));
+        ret = tams_create_flow(s, &mc->flow);
+        if (ret < 0)
+            return ret;
+    }
+    return 0;
+}
+
+/*
+ * For every multi-Flow pinned to an existing id:
+ *
+ * - GET and validate it
+ * - match every one of its member streams that wasn't itself explicitly pinned
+ *   against a remaining, essence-type-compatible entry in the fetched 
flow_collection.
+ *
+ * Hard error on ambiguity (more than one equally-valid candidate) or an 
unclaimed
+ * flow_collection entry or a member stream matching nothing.
+ */
+static int tams_match_pinned_multi_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    for (int i = 0; i < c->nb_multi_flow_ctxs; i++) {
+        TAMSMultiFlowContext *mc = &c->multi_flow_ctxs[i];
+        uint8_t claimed[TAMS_MAX_COLLECTION_ITEMS] = { 0 };
+        const char *item_type[TAMS_MAX_COLLECTION_ITEMS] = { 0 };
+        int ret;
+
+        if (!mc->has_flow_id)
+            continue;
+
+        ret = tams_fetch_flow(s, mc->flow_id, &mc->flow);
+        if (ret < 0)
+            return ret;
+        if (mc->flow.format != TAMS_FORMAT_MULTI) {
+            av_log(s, AV_LOG_ERROR, "TAMS: pinned multi_flow=%d Flow %s is not 
a multi-Flow\n",
+                   mc->index, mc->flow_id);
+            return AVERROR(EINVAL);
+        }
+
+        /* mark entries already claimed by an explicit id= pin on a member 
stream */
+        for (int j = 0; j < mc->nb_container_indices; j++) {
+            TAMSContainerContext *cc = 
&c->container_ctxs[mc->container_indices[j]];
+            for (int k = 0; k < cc->nb_streams; k++) {
+                if (!cc->flow_ctxs[k].has_flow_id)
+                    continue;
+                for (int m = 0; m < mc->flow.nb_flow_collection_items; m++) {
+                    if (!strcmp(mc->flow.flow_collection_items[m].id, 
cc->flow_ctxs[k].flow_id)) {
+                        claimed[m] = 1;
+                        break;
+                    }
+                }
+            }
+        }
+
+        /*
+         * Derive each container entry's essence type from its own Flow's 
format
+         * when the role is not one of "video"/"audio"/"data".
+         */
+        for (int m = 0; m < mc->flow.nb_flow_collection_items; m++) {
+            TAMSFlowCollectionItem *item = &mc->flow.flow_collection_items[m];
+            TAMSFlow *member;
+
+            if (claimed[m] || !strcmp(item->role, "video") ||
+                !strcmp(item->role, "audio") || !strcmp(item->role, "data"))
+                continue;
+
+            member = av_mallocz(sizeof(*member));
+            if (!member)
+                return AVERROR(ENOMEM);
+            ret = tams_fetch_flow(s, item->id, member);
+            if (ret >= 0)
+                item_type[m] = member->format == TAMS_FORMAT_VIDEO ? "video" :
+                               member->format == TAMS_FORMAT_AUDIO ? "audio" :
+                               member->format == TAMS_FORMAT_DATA  ? "data"  : 
NULL;
+            av_free(member);
+            if (ret < 0)
+                return ret;
+        }
+
+        /*
+         * Match every unpinned member stream against a remaining
+         * essence-type compatible flow_collection entry
+         */
+        for (int j = 0; j < mc->nb_container_indices; j++) {
+            TAMSContainerContext *cc = 
&c->container_ctxs[mc->container_indices[j]];
+
+            for (int k = 0; k < cc->nb_streams; k++) {
+                TAMSFlowContext *fc = &cc->flow_ctxs[k];
+                enum AVMediaType want;
+                const char *want_role;
+                int match = -1;
+
+                if (fc->has_flow_id)
+                    continue;
+
+                want = s->streams[cc->stream_indices[k]]->codecpar->codec_type;
+                want_role = want == AVMEDIA_TYPE_VIDEO ? "video" :
+                           want == AVMEDIA_TYPE_AUDIO ? "audio" : "data";
+
+                for (int m = 0; m < mc->flow.nb_flow_collection_items; m++) {
+                    const char *type = item_type[m] ? item_type[m]
+                                                    : 
mc->flow.flow_collection_items[m].role;
+                    if (claimed[m] || strcmp(type, want_role))
+                        continue;
+                    if (match >= 0) {
+                        av_log(s, AV_LOG_ERROR,
+                               "TAMS: ambiguous match for stream %d against 
pinned multi_flow=%d's "
+                               "flow_collection (more than one unclaimed '%s' 
entry)\n",
+                               cc->stream_indices[k], mc->index, want_role);
+                        return AVERROR(EINVAL);
+                    }
+                    match = m;
+                }
+                if (match < 0) {
+                    av_log(s, AV_LOG_ERROR,
+                           "TAMS: no matching flow_collection entry for stream 
%d "
+                           "against pinned multi_flow=%d\n",
+                           cc->stream_indices[k], mc->index);
+                    return AVERROR(EINVAL);
+                }
+
+                claimed[match] = 1;
+                av_strlcpy(fc->flow_id, 
mc->flow.flow_collection_items[match].id, sizeof(fc->flow_id));
+                fc->has_flow_id = 1;
+            }
+        }
+
+        for (int m = 0; m < mc->flow.nb_flow_collection_items; m++) {
+            if (!claimed[m]) {
+                av_log(s, AV_LOG_ERROR,
+                       "TAMS: pinned multi_flow=%d's flow_collection entry %s 
(role=%s) "
+                       "was not claimed by any mapped stream\n",
+                       mc->index, mc->flow.flow_collection_items[m].id,
+                       mc->flow.flow_collection_items[m].role);
+                return AVERROR(EINVAL);
+            }
+        }
+    }
+
+    return 0;
+}
+
+/*
+ * POST /flows/{owner_flow_id}/storage {"limit":1}. Stash the put_url/
+ * object_id for the *next* segment. Safe to do a full segment ahead of
+ * when it's needed based on the store's 
min_object_timeout/min_presigned_url_timeout
+ * guarantees.
+ */
+static int tams_alloc_next_storage(AVFormatContext *s, TAMSContainerContext 
*cc)
+{
+    /* only presigned PUT URLs are supported */
+    static const char body[] = "{\"limit\":1,\"presigned\":true}";
+    TAMSMuxContext *c = s->priv_data;
+    char url[2100];
+    AVBPrint resp;
+    TAMSMediaObject *objects = NULL;
+    int nb_objects = 0;
+    int ret;
+
+    ret = ff_tams_flow_subresource_url(c->flows_base_url, cc->owner_flow_id, 
"storage",
+                                       url, sizeof(url));
+    if (ret < 0)
+        return ret;
+
+    ret = tams_request(s, url, "POST", (const uint8_t *)body, strlen(body),
+                       "application/json", &resp);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: failed to allocate storage for Flow %s: 
%s\n",
+               cc->owner_flow_id, av_err2str(ret));
+        return ret;
+    }
+
+    ret = ff_tams_storage_allocation_from_json(resp.str, &objects, 
&nb_objects);
+    av_bprint_finalize(&resp, NULL);
+    if (ret < 0 || nb_objects < 1) {
+        av_log(s, AV_LOG_ERROR, "TAMS: malformed storage-allocation response 
for Flow %s\n",
+               cc->owner_flow_id);
+        av_free(objects);
+        return ret < 0 ? ret : AVERROR_INVALIDDATA;
+    }
+
+    av_freep(&cc->next_put_url);
+    av_freep(&cc->next_object_id);
+    cc->next_put_url   = av_strdup(objects[0].put_url);
+    cc->next_object_id = av_strdup(objects[0].object_id);
+    av_strlcpy(cc->next_put_content_type, objects[0].put_content_type,
+              sizeof(cc->next_put_content_type));
+    av_free(objects);
+    if (!cc->next_put_url || !cc->next_object_id)
+        return AVERROR(ENOMEM);
+
+    return 0;
+}
+
+/*
+ * Determine ts_offset of the current object: the value a reader adds to a
+ * timestamp inside the object to get its TAI time on the Flow timeline
+ * (flow_ts = media_ts + ts_offset).
+ *
+ * A packet's Flow time is start_tai_ns plus its input timestamp. The
+ * timestamp written into the object is its input timestamp plus two shifts:
+ *
+ *   - ts_shift: set by tams_set_ts_shift() when the object starts
+ *   - mux_ts_offset: added by lavf when the first timestamps written would
+ *     be negative e.g. B-frame dts or audio priming.
+ *
+ * So ts_offset = start_tai_ns - (ts_shift + mux_ts_offset). It is calculated
+ * in the reference stream's time base.
+ *
+ * Raw elementary-stream formats store no timestamps. In this case
+ * a reader numbers their frames from 0 at the object's first packet and
+ * therefore ts_offset is that packet's Flow time.
+ */
+static int64_t tams_segment_ts_offset(const TAMSMuxContext *c, const 
TAMSContainerContext *cc)
+{
+    const AVFormatContext *oc = cc->sub_ctx;
+    const AVStream *st = oc->streams[cc->reference_stream_index];
+    int64_t shift;
+
+    if (oc->oformat->flags & AVFMT_NOTIMESTAMPS)
+        return c->start_tai_ns + (cc->first_ns != AV_NOPTS_VALUE ? 
cc->first_ns : cc->segment_start_ns);
+
+    shift = av_rescale_q(cc->ts_shift, cc->ts_shift_tb, st->time_base) + 
cffstream(st)->mux_ts_offset;
+    return c->start_tai_ns - av_rescale_q(shift, st->time_base, (AVRational){ 
1, TAMS_TIMEBASE });
+}
+
+/*
+ * Set the timestamp shift for the object that pkt (of stream ist) starts.
+ *
+ * The first object is not shifted: it keeps the input's timestamps, so any
+ * audio priming stays before the start of the Flow. A later object starts
+ * at 0 at its origin for the pts of the keyframe it was cut on.
+ */
+static void tams_set_ts_shift(const TAMSMuxContext *c, TAMSContainerContext 
*cc,
+                              const AVStream *ist, const AVPacket *pkt)
+{
+    const char *name = cc->oformat->name;
+    AVRational tb = ist->time_base;
+    int first = !cc->segment_index && !cc->has_prev;
+    int64_t origin = pkt->pts != AV_NOPTS_VALUE ? pkt->pts : 0;
+
+    /*
+     * MPEG-TS follows appnote 0002: PTS is the Flow time at 90 kHz modulo 2^33
+     * and ts_offset the time the counter last rolled over.
+     */
+    if (!strcmp(name, "mpegts")) {
+        int64_t start90 = av_rescale(c->start_tai_ns, 90000, TAMS_TIMEBASE);
+        int64_t abs90   = FFMAX(av_rescale(c->start_tai_ns + 
av_rescale_q(origin, tb, (AVRational){ 1, TAMS_TIMEBASE }),
+                                           90000, TAMS_TIMEBASE), 0);
+
+        cc->ts_shift    = start90 - (abs90 & ~((INT64_C(1) << 33) - 1));
+        cc->ts_shift_tb = (AVRational){ 1, 90000 };
+        return;
+    }
+
+    cc->ts_shift_tb = tb;
+
+    /* The first object keeps the input's timestamps, so any priming stays 
negative. */
+    if (first) {
+        cc->ts_shift = 0;
+        return;
+    }
+
+    cc->ts_shift = -origin;
+}
+
+/* Write pkt to the current object, rescaled and shifted into its stream's 
time base */
+static int tams_write_object(AVFormatContext *s, AVFormatContext *oc, int 
sub_idx,
+                             int64_t shift, AVRational shift_tb, AVPacket *pkt)
+{
+    AVRational itb = s->streams[pkt->stream_index]->time_base;
+    AVRational otb = oc->streams[sub_idx]->time_base;
+    int64_t pts = pkt->pts, dts = pkt->dts, duration = pkt->duration;
+    int stream_index = pkt->stream_index;
+    AVRational time_base = pkt->time_base;
+    int64_t off = av_rescale_q(shift, shift_tb, otb);
+    int ret;
+
+    pkt->stream_index = sub_idx;
+    av_packet_rescale_ts(pkt, itb, otb);
+    if (pkt->pts != AV_NOPTS_VALUE)
+        pkt->pts += off;
+    if (pkt->dts != AV_NOPTS_VALUE)
+        pkt->dts += off;
+    ret = av_write_frame(oc, pkt);
+    pkt->pts          = pts;
+    pkt->dts          = dts;
+    pkt->duration     = duration;
+    pkt->stream_index = stream_index;
+    pkt->time_base    = time_base;
+    return ret;
+}
+
+static int tams_restart_container_mux(AVFormatContext *s, TAMSContainerContext 
*cc)
+{
+    int ret;
+
+    ret = tams_build_container_mux(s, cc);
+    if (ret < 0)
+        return ret;
+
+    /*
+     * Only the first object holds the encoder's priming. A later object's
+     * header must not declare any.
+     */
+    for (int i = 0; i < cc->sub_ctx->nb_streams; i++)
+        cc->sub_ctx->streams[i]->codecpar->initial_padding = 0;
+    if (!strcmp(cc->oformat->name, "mp3")) {
+        ret = av_opt_set_int(cc->sub_ctx->priv_data, "write_xing", 0, 0);
+        if (ret < 0)
+            return ret;
+    }
+
+    ret = avio_open_dyn_buf(&cc->sub_ctx->pb);
+    if (ret < 0)
+        return ret;
+    ret = avformat_write_header(cc->sub_ctx, NULL);
+    if (ret < 0)
+        av_log(s, AV_LOG_ERROR, "TAMS: nested muxer write_header failed: 
%s\n", av_err2str(ret));
+    return ret;
+}
+
+/* Move the current object to cc->prev, with the timerange ending at end_ns. */
+static int tams_close_current(AVFormatContext *s, TAMSContainerContext *cc, 
int64_t end_ns)
+{
+    TAMSMuxContext *c = s->priv_data;
+    TAMSClosingObject *o = &cc->prev;
+
+    if (!cc->next_put_url) {
+        av_log(s, AV_LOG_ERROR, "TAMS: no pre-allocated storage for Flow 
%s\n", cc->owner_flow_id);
+        return AVERROR(EINVAL);
+    }
+
+    o->ts_offset   = tams_segment_ts_offset(c, cc);
+    o->sub_ctx     = cc->sub_ctx;
+    o->put_url     = cc->next_put_url;
+    o->object_id   = cc->next_object_id;
+    av_strlcpy(o->put_content_type, cc->next_put_content_type, 
sizeof(o->put_content_type));
+    o->start_ns    = cc->segment_start_ns;
+    o->end_ns      = FFMAX(end_ns, cc->segment_start_ns + 1);
+    o->last_ref_ns = cc->last_ref_ns;
+    o->nb_pending  = cc->nb_streams - 1;
+    memset(cc->passed_cut, 0, cc->nb_streams);
+    cc->sub_ctx        = NULL;
+    cc->next_put_url   = NULL;
+    cc->next_object_id = NULL;
+    cc->has_prev         = 1;
+    cc->has_segment_data = 0;
+    return 0;
+}
+
+/*
+ * Write the trailer of cc->prev, PUT its bytes to the container's owner Flow
+ * and POST one /segments registration.
+ */
+static int tams_flush_segment(AVFormatContext *s, TAMSContainerContext *cc)
+{
+    TAMSMuxContext *c = s->priv_data;
+    TAMSClosingObject *o = &cc->prev;
+    uint8_t *data = NULL;
+    int size, ret;
+    TAMSFlowSegment seg = { 0 };
+    char segs_url[2100];
+    AVBPrint json;
+
+    cc->has_prev = 0;
+    ret = av_write_trailer(o->sub_ctx);
+    size = avio_close_dyn_buf(o->sub_ctx->pb, &data);
+    o->sub_ctx->pb = NULL;
+    avformat_free_context(o->sub_ctx);
+    o->sub_ctx = NULL;
+    if (ret < 0)
+        goto end;
+
+    ret = tams_request(s, o->put_url, "PUT", data, size,
+                       o->put_content_type[0] ? o->put_content_type : NULL, 
NULL);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: failed to PUT segment bytes for Flow 
%s: %s\n",
+               cc->owner_flow_id, av_err2str(ret));
+        goto end;
+    }
+
+    av_strlcpy(seg.object_id, o->object_id, sizeof(seg.object_id));
+    seg.timerange.has_start       = 1;
+    seg.timerange.start_inclusive = 1;
+    seg.timerange.start           = c->start_tai_ns + o->start_ns;
+    seg.timerange.has_end         = 1;
+    seg.timerange.end_inclusive   = 0;
+    seg.timerange.end             = c->start_tai_ns + o->end_ns;
+    seg.ts_offset = o->ts_offset;
+    if (o->last_ref_ns != INT64_MIN && o->last_ref_ns < o->end_ns) {
+        seg.last_duration     = o->end_ns - o->last_ref_ns;
+        seg.has_last_duration = 1;
+    }
+
+    av_bprint_init(&json, 0, INT_MAX);
+    ret = ff_tams_flow_segment_to_json(&json, &seg);
+    if (ret >= 0)
+        ret = ff_tams_flow_subresource_url(c->flows_base_url, 
cc->owner_flow_id, "segments",
+                                           segs_url, sizeof(segs_url));
+    if (ret >= 0)
+        ret = tams_request(s, segs_url, "POST", (const uint8_t *)json.str, 
json.len,
+                           "application/json", NULL);
+    av_bprint_finalize(&json, NULL);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "TAMS: failed to register segment for Flow %s: 
%s\n",
+               cc->owner_flow_id, av_err2str(ret));
+        goto end;
+    }
+
+    cc->total_bytes += size;
+    cc->total_ns    += o->end_ns - o->start_ns;
+    cc->max_bit_rate = FFMAX(cc->max_bit_rate,
+                             av_rescale(size * INT64_C(8), TAMS_TIMEBASE, 
o->end_ns - o->start_ns));
+    if (!cc->segment_index++)
+        ret = tams_set_created_flow_status(s, cc, "ingesting");
+
+end:
+    av_freep(&o->put_url);
+    av_freep(&o->object_id);
+    av_free(data);
+    return ret;
+}
+
+/*
+ * DELETE the Flows this muxer created, multi-Flows first so no multi-Flow is
+ * left referencing a deleted member. Best effort: failures are only logged.
+ */
+static void tams_delete_created_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    char url[2100];
+
+    for (int i = 0; i < c->nb_multi_flow_ctxs; i++) {
+        TAMSMultiFlowContext *mc = &c->multi_flow_ctxs[i];
+        if (!mc->created || ff_tams_flow_url(c->flows_base_url, mc->flow_id, 
url, sizeof(url)) < 0)
+            continue;
+        if (tams_request(s, url, "DELETE", NULL, 0, NULL, NULL) < 0)
+            av_log(s, AV_LOG_WARNING, "TAMS: failed to delete multi-Flow 
%s\n", mc->flow_id);
+        mc->created = 0;
+    }
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+        for (int j = 0; j < cc->nb_streams; j++) {
+            TAMSFlowContext *fc = &cc->flow_ctxs[j];
+            if (!fc->created || ff_tams_flow_url(c->flows_base_url, 
fc->flow_id, url, sizeof(url)) < 0)
+                continue;
+            if (tams_request(s, url, "DELETE", NULL, 0, NULL, NULL) < 0)
+                av_log(s, AV_LOG_WARNING, "TAMS: failed to delete Flow %s\n", 
fc->flow_id);
+            fc->created = 0;
+        }
+    }
+}
+
+static int tams_init_flows(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int ret;
+
+    ret = tams_validate_streams(s);
+    if (ret < 0)
+        return ret;
+
+    if (c->start_timestamp_str) {
+        ret = ff_tams_timestamp_from_str(c->start_timestamp_str, 
&c->start_tai_ns);
+        if (ret < 0) {
+            av_log(s, AV_LOG_ERROR, "Invalid -start_timestamp '%s'\n", 
c->start_timestamp_str);
+            return ret;
+        }
+    } else {
+        c->start_tai_ns = av_gettime() * INT64_C(1000);
+    }
+
+    ret = tams_derive_base_url(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_build_containers(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_build_stream_maps(s);
+    if (ret < 0)
+        return ret;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+
+        cc->reference_stream_index = 0;
+        for (int j = 0; j < cc->nb_streams; j++) {
+            if (cc->sub_ctx->streams[j]->codecpar->codec_type == 
AVMEDIA_TYPE_VIDEO) {
+                cc->reference_stream_index = j;
+                break;
+            }
+        }
+    }
+
+    /*
+     * Everything which can be checked is checked before any Flow is created,
+     * so a bad -flow_map or -segment_duration leaves nothing on the store.
+     */
+    ret = tams_fetch_service_limits(s);
+    if (ret < 0)
+        return ret;
+
+    /*
+     * Match existing multi-Flows' members first, so an implicitly-matched
+     * member takes a GET+validate path below rather than creating a brand new 
Flow.
+     */
+    ret = tams_match_pinned_multi_flows(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_check_mono_flows(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_check_segment_durations(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_create_mono_flows(s);
+    if (ret < 0)
+        return ret;
+
+    ret = tams_create_multi_flows(s);
+    if (ret < 0)
+        return ret;
+
+    /*
+     * A shared container (nb_streams > 1) is registered once against its
+     * owning multi-Flow, not against each member.
+     */
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+
+        if (cc->nb_streams == 1) {
+            av_strlcpy(cc->owner_flow_id, cc->flow_ctxs[0].flow_id, 
sizeof(cc->owner_flow_id));
+            continue;
+        }
+        for (int j = 0; j < c->nb_multi_flow_ctxs; j++) {
+            if (c->multi_flow_ctxs[j].index == cc->multi_flow_index) {
+                av_strlcpy(cc->owner_flow_id, c->multi_flow_ctxs[j].flow_id, 
sizeof(cc->owner_flow_id));
+                break;
+            }
+        }
+    }
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        TAMSContainerContext *cc = &c->container_ctxs[i];
+
+        ret = avio_open_dyn_buf(&cc->sub_ctx->pb);
+        if (ret < 0)
+            return ret;
+
+        ret = avformat_write_header(cc->sub_ctx, NULL);
+        if (ret < 0) {
+            av_log(s, AV_LOG_ERROR, "TAMS: nested muxer write_header failed: 
%s\n", av_err2str(ret));
+            return ret;
+        }
+
+        cc->has_segment_data = 0;
+        cc->segment_start_ns = 0;
+        cc->next_boundary_ns = cc->segment_duration_ns;
+        cc->passed_cut = av_calloc(cc->nb_streams, 1);
+        if (!cc->passed_cut)
+            return AVERROR(ENOMEM);
+
+        ret = tams_alloc_next_storage(s, cc);
+        if (ret < 0)
+            return ret;
+    }
+
+    tams_log_mapping_summary(s);
+
+    return 0;
+}
+
+/* A failed header deletes any Flows it created, as no segment was written to 
them. */
+static int tams_write_header(AVFormatContext *s)
+{
+    int ret = tams_init_flows(s);
+
+    if (ret < 0)
+        tams_delete_created_flows(s);
+    return ret;
+}
+
+static int tams_write_packet(AVFormatContext *s, AVPacket *pkt)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int container_idx = c->stream_to_container[pkt->stream_index];
+    int sub_idx = c->stream_to_subindex[pkt->stream_index];
+    TAMSContainerContext *cc = &c->container_ctxs[container_idx];
+    AVStream *ist = s->streams[pkt->stream_index];
+    int64_t ts_ns = AV_NOPTS_VALUE;
+    int ret;
+
+    if (cc->error)
+        return cc->error;
+
+    if (pkt->pts != AV_NOPTS_VALUE)
+        ts_ns = av_rescale_q(pkt->pts, ist->time_base, (AVRational){ 1, 
TAMS_TIMEBASE });
+
+    if (cc->has_prev && sub_idx != cc->reference_stream_index && 
!cc->passed_cut[sub_idx]) {
+        /* still before the cut so the packet belongs to the previous object */
+        if (ts_ns != AV_NOPTS_VALUE && ts_ns < cc->prev.end_ns)
+            return tams_write_object(s, cc->prev.sub_ctx, sub_idx, 
cc->ts_shift_prev,
+                                     cc->ts_shift_prev_tb, pkt);
+        cc->passed_cut[sub_idx] = 1;
+        if (!--cc->prev.nb_pending && (ret = tams_flush_segment(s, cc)) < 0)
+            return cc->error = ret;
+    }
+
+    /* cut at the first reference keyframe at/after the planned boundary */
+    if (sub_idx == cc->reference_stream_index && (pkt->flags & 
AV_PKT_FLAG_KEY) &&
+        cc->has_segment_data && ts_ns != AV_NOPTS_VALUE && ts_ns >= 
cc->next_boundary_ns) {
+        if (cc->has_prev && (ret = tams_flush_segment(s, cc)) < 0)
+            return cc->error = ret;
+        cc->ts_shift_prev    = cc->ts_shift;
+        cc->ts_shift_prev_tb = cc->ts_shift_tb;
+        if ((ret = tams_close_current(s, cc, ts_ns)) < 0 ||
+            (ret = tams_restart_container_mux(s, cc)) < 0 ||
+            (ret = tams_alloc_next_storage(s, cc)) < 0)
+            return cc->error = ret;
+        if (!cc->prev.nb_pending && (ret = tams_flush_segment(s, cc)) < 0)
+            return cc->error = ret;
+
+        tams_set_ts_shift(c, cc, ist, pkt);
+        cc->has_segment_data = 1;
+        cc->segment_start_ns = ts_ns;
+        cc->segment_end_ns   = INT64_MIN;
+        cc->first_ns         = ts_ns;
+        cc->last_ref_ns      = INT64_MIN;
+        cc->next_boundary_ns = ts_ns + cc->segment_duration_ns;
+    }
+
+    if (!cc->has_segment_data) {
+        cc->has_segment_data = 1;
+        cc->segment_end_ns   = INT64_MIN;
+        cc->first_ns         = ts_ns;
+        cc->last_ref_ns      = INT64_MIN;
+        tams_set_ts_shift(c, cc, ist, pkt);
+        /* priming (negative timestamps) stays before the timeline start */
+        if (sub_idx == cc->reference_stream_index && ts_ns != AV_NOPTS_VALUE) {
+            cc->segment_start_ns = FFMAX(ts_ns, 0);
+            cc->next_boundary_ns  = cc->segment_start_ns + 
cc->segment_duration_ns;
+        }
+    }
+
+    /*
+     * The first segment starts at the earliest packet of any stream, e.g.
+     * audio ahead of video delayed for B-frames, so it is not left outside the
+     * segment's timerange. Priming (negative) timestamps stay before it.
+     */
+    if (!cc->segment_index && !cc->has_prev && ts_ns != AV_NOPTS_VALUE && 
ts_ns >= 0 &&
+        ts_ns < cc->segment_start_ns)
+        cc->segment_start_ns = ts_ns;
+
+    if (ts_ns != AV_NOPTS_VALUE) {
+        cc->segment_end_ns = FFMAX(cc->segment_end_ns, ts_ns +
+                                   av_rescale_q(pkt->duration, ist->time_base,
+                                                (AVRational){ 1, TAMS_TIMEBASE 
}));
+        if (cc->first_ns == AV_NOPTS_VALUE)
+            cc->first_ns = ts_ns;
+        if (sub_idx == cc->reference_stream_index && pkt->size)
+            cc->last_ref_ns = FFMAX(cc->last_ref_ns, ts_ns);
+    }
+
+    return tams_write_object(s, cc->sub_ctx, sub_idx, cc->ts_shift, 
cc->ts_shift_tb, pkt);
+}
+
+static int tams_finalize_container(AVFormatContext *s, TAMSContainerContext 
*cc)
+{
+    int ret;
+
+    if (cc->error || !cc->sub_ctx || !cc->sub_ctx->pb)
+        return 0;
+
+    if (cc->has_prev && (ret = tams_flush_segment(s, cc)) < 0)
+        return ret;
+
+    if (cc->has_segment_data) {
+        int64_t end_ns = cc->segment_end_ns != INT64_MIN ? cc->segment_end_ns
+                                                         : 
cc->next_boundary_ns;
+        if ((ret = tams_close_current(s, cc, end_ns)) < 0)
+            return ret;
+        return tams_flush_segment(s, cc);
+    }
+    return 0;
+}
+
+/* avg_bit_rate/max_bit_rate in kbit/s, per appnote 0013 */
+static void tams_set_bit_rates(AVFormatContext *s, TAMSContainerContext *cc)
+{
+    TAMSMuxContext *c = s->priv_data;
+    TAMSFlow *flow = NULL;
+
+    if (!cc->total_ns)
+        return;
+    if (cc->nb_streams == 1) {
+        if (cc->flow_ctxs[0].created)
+            flow = &cc->flow_ctxs[0].flow;
+    } else {
+        for (int i = 0; i < c->nb_multi_flow_ctxs; i++)
+            if (c->multi_flow_ctxs[i].created &&
+                !strcmp(c->multi_flow_ctxs[i].flow_id, cc->owner_flow_id))
+                flow = &c->multi_flow_ctxs[i].flow;
+    }
+    if (!flow)
+        return;
+    flow->avg_bit_rate = av_rescale(cc->total_bytes * 8, TAMS_TIMEBASE, 
cc->total_ns * INT64_C(1000));
+    flow->max_bit_rate = cc->max_bit_rate / 1000;
+}
+
+static int tams_write_trailer(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int ret = 0;
+
+    for (int i = 0; i < c->nb_container_ctxs; i++) {
+        int r = tams_finalize_container(s, &c->container_ctxs[i]);
+        if (r < 0 && ret >= 0)
+            ret = r;
+        tams_set_bit_rates(s, &c->container_ctxs[i]);
+    }
+
+    if (ret >= 0)
+        ret = tams_set_created_flow_status(s, NULL, "closed_complete");
+
+    return ret;
+}
+
+static av_cold int tams_init(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+    int ret;
+
+    ret = tams_parse_flow_map(c->flow_map_str, s->nb_streams,
+                              &c->container_ctxs, &c->nb_container_ctxs,
+                              &c->multi_flow_ctxs, &c->nb_multi_flow_ctxs);
+    if (ret < 0) {
+        av_log(s, AV_LOG_ERROR, "Invalid -flow_map: %s\n",
+               c->flow_map_str ? c->flow_map_str : "(default)");
+        return ret;
+    }
+
+    /*
+     * This muxer is AVFMT_NOFILE (it never opens s->pb). Every request is
+     * issued against derived URLs, so capture the generic -headers AVOption
+     * here for ff_tams_request() to replay on every same-host request.
+     */
+    if (c->headers_str) {
+        ret = av_dict_set(&c->avio_opts, "headers", c->headers_str, 0);
+        if (ret < 0)
+            return ret;
+    }
+
+    return 0;
+}
+
+static av_cold void tams_deinit(AVFormatContext *s)
+{
+    TAMSMuxContext *c = s->priv_data;
+
+    tams_free_container_ctxs(c->container_ctxs, c->nb_container_ctxs);
+    c->container_ctxs    = NULL;
+    c->nb_container_ctxs = 0;
+
+    tams_free_multi_flow_ctxs(c->multi_flow_ctxs, c->nb_multi_flow_ctxs);
+    c->multi_flow_ctxs    = NULL;
+    c->nb_multi_flow_ctxs = 0;
+
+    av_freep(&c->stream_to_container);
+    av_freep(&c->stream_to_subindex);
+    av_dict_free(&c->avio_opts);
+}
+
+#define OFFSET(x) offsetof(TAMSMuxContext, x)
+#define FLAGS AV_OPT_FLAG_ENCODING_PARAM
+
+static const AVOption tams_options[] = {
+    { "flow_map", "map AVStreams to Flows/multi-Flows: space-separated "
+        "\"flow=streams=0,id=<uuid>,source_id=<uuid>,multi_flow=N\" and "
+        
"\"multi_flow=N,id=<uuid>,source_id=<uuid>,label=<text>,description=<text>,"
+        "tags.<name>=<text>\" tokens (a mono Flow's label/description/tags 
come from its "
+        "AVStream's metadata instead; default, and for any stream not 
mentioned: its own "
+        "standalone mono Flow)",
+        OFFSET(flow_map_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "container", "container format (default: codec-specific raw ES for a 
single-stream "
+        "container, else mp4)",
+        OFFSET(container_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS 
},
+    { "start_timestamp", "TAMS timestamp string overriding the wall-clock 
timeline origin",
+        OFFSET(start_timestamp_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, 
FLAGS },
+    { "headers", "extra HTTP headers (e.g. \"Authorization: Bearer 
<token>\\r\\n\") to send "
+        "with every TAMS request",
+        OFFSET(headers_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
+    { "segment_duration", "target segment duration in seconds (-1=auto: 
existing flow's segment_duration, else 2)",
+        OFFSET(segment_duration_s), AV_OPT_TYPE_INT64, {.i64 = -1}, -1, 
INT64_MAX, FLAGS },
+    { "retry_max", "maximum retry attempts for transient HTTP errors",
+        OFFSET(retry_max), AV_OPT_TYPE_INT, {.i64 = 3}, 0, INT_MAX, FLAGS },
+    { "retry_backoff", "initial retry backoff in microseconds, doubling on 
each attempt",
+        OFFSET(retry_backoff_us), AV_OPT_TYPE_INT64, {.i64 = 500000}, 0, 
INT64_MAX, FLAGS },
+    { NULL },
+};
+
+static const AVClass tams_muxer_class = {
+    .class_name = "tams",
+    .item_name  = av_default_item_name,
+    .option     = tams_options,
+    .version    = LIBAVUTIL_VERSION_INT,
+};
+
+const FFOutputFormat ff_tams_muxer = {
+    .p.name         = "tams",
+    .p.long_name    = NULL_IF_CONFIG_SMALL("TAMS (Time-Addressable Media 
Store)"),
+    .p.audio_codec  = AV_CODEC_ID_AAC,
+    .p.video_codec  = AV_CODEC_ID_H264,
+    .p.subtitle_codec = AV_CODEC_ID_SUBRIP,
+    .p.flags        = AVFMT_GLOBALHEADER | AVFMT_NOFILE | AVFMT_TS_NEGATIVE,
+    .p.priv_class   = &tams_muxer_class,
+    .priv_data_size = sizeof(TAMSMuxContext),
+    .init           = tams_init,
+    .deinit         = tams_deinit,
+    .write_header   = tams_write_header,
+    .write_packet   = tams_write_packet,
+    .write_trailer  = tams_write_trailer,
+};
diff --git a/libavformat/tests/.gitignore b/libavformat/tests/.gitignore
index 337edf67711..82f5cd9ebb3 100644
--- a/libavformat/tests/.gitignore
+++ b/libavformat/tests/.gitignore
@@ -14,6 +14,7 @@
 /srtp
 /tams
 /tamsdec
+/tamsenc
 /url
 /seek_utils
 /http
diff --git a/libavformat/tests/tamsenc.c b/libavformat/tests/tamsenc.c
new file mode 100644
index 00000000000..3c96109b2ff
--- /dev/null
+++ b/libavformat/tests/tamsenc.c
@@ -0,0 +1,634 @@
+/*
+ * Copyright (C) 2026 Hoot Works Ltd
+ * Author    (C) 2026 Nick Ryan <[email protected]>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Tests for TAMS muxer internals.
+ *
+ * @author Nick Ryan
+ */
+
+#include "libavformat/tamsenc.c"
+
+#include "libavcodec/codec_id.h"
+#include "libavcodec/packet.h"
+
+#include <stdio.h>
+
+#define FAIL(msg, ...) do { \
+    printf("FAIL: " msg "\n", ##__VA_ARGS__); \
+    return 1; \
+} while (0)
+
+/* ====================================================================
+ * Flow map test helpers
+ * ==================================================================== */
+
+static void free_result(TAMSContainerContext *containers, int nb_containers,
+                         TAMSMultiFlowContext *multis, int nb_multis)
+{
+    tams_free_container_ctxs(containers, nb_containers);
+    tams_free_multi_flow_ctxs(multis, nb_multis);
+}
+
+static int test_flow_map_fails(const char *test_name, const char *str, int 
nb_streams)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    ret = tams_parse_flow_map(str, nb_streams, &containers, &nb_containers, 
&multis, &nb_multis);
+    if (ret >= 0) {
+        free_result(containers, nb_containers, multis, nb_multis);
+        FAIL("%s: expected failure but got success", test_name);
+    }
+
+    printf("OK: %s (correctly failed with %d)\n", test_name, ret);
+    return 0;
+}
+
+/* ====================================================================
+ * Flow map tests
+ * ==================================================================== */
+
+static int test_flow_map_default(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    ret = tams_parse_flow_map(NULL, 3, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_default: returned %d", ret);
+    if (nb_containers != 3 || nb_multis != 0)
+        FAIL("flow_map_default: expected 3 containers/0 multis, got %d/%d",
+             nb_containers, nb_multis);
+    for (int i = 0; i < 3; i++) {
+        if (containers[i].nb_streams != 1 || containers[i].stream_indices[0] 
!= i ||
+            containers[i].has_multi_flow)
+            FAIL("flow_map_default: container %d wrong", i);
+    }
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_default\n");
+    return 0;
+}
+
+static int test_flow_map_empty_string(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    ret = tams_parse_flow_map("", 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0 || nb_containers != 2 || nb_multis != 0)
+        FAIL("flow_map_empty_string: expected default, got ret=%d 
nb_containers=%d nb_multis=%d",
+             ret, nb_containers, nb_multis);
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_empty_string\n");
+    return 0;
+}
+
+static int test_flow_map_explicit_split(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    ret = tams_parse_flow_map("flow=streams=0 flow=streams=1", 2,
+                              &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_explicit_split: returned %d", ret);
+    if (nb_containers != 2 || nb_multis != 0)
+        FAIL("flow_map_explicit_split: expected 2 containers, got %d", 
nb_containers);
+    if (containers[0].nb_streams != 1 || containers[0].stream_indices[0] != 0)
+        FAIL("flow_map_explicit_split: container 0 wrong");
+    if (containers[1].nb_streams != 1 || containers[1].stream_indices[0] != 1)
+        FAIL("flow_map_explicit_split: container 1 wrong");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_explicit_split\n");
+    return 0;
+}
+
+static int test_flow_map_unmentioned_stream_gets_default(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    /* stream 1 is never mentioned -- should default to its own standalone 
mono Flow */
+    ret = 
tams_parse_flow_map("flow=streams=0,id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34",
+                              2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_unmentioned_stream_gets_default: returned %d", ret);
+    if (nb_containers != 2 || nb_multis != 0)
+        FAIL("flow_map_unmentioned_stream_gets_default: expected 2 containers, 
got %d",
+             nb_containers);
+    if (!containers[0].flow_ctxs[0].has_flow_id)
+        FAIL("flow_map_unmentioned_stream_gets_default: container 0 should be 
pinned");
+    if (containers[1].nb_streams != 1 || containers[1].stream_indices[0] != 1 
||
+        containers[1].has_multi_flow || containers[1].flow_ctxs[0].has_flow_id)
+        FAIL("flow_map_unmentioned_stream_gets_default: container 1 should be 
a "
+             "plain default for stream 1");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_unmentioned_stream_gets_default\n");
+    return 0;
+}
+
+static int test_flow_map_id_pin(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str = "flow=streams=0,id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34";
+
+    ret = tams_parse_flow_map(str, 1, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_id_pin: returned %d", ret);
+    if (nb_containers != 1 || containers[0].nb_streams != 1)
+        FAIL("flow_map_id_pin: expected 1 container/1 flow");
+    if (!containers[0].flow_ctxs[0].has_flow_id ||
+        strcmp(containers[0].flow_ctxs[0].flow_id, 
"4f79cfd1-c057-47f4-8e4d-1b126ca7bf34"))
+        FAIL("flow_map_id_pin: wrong flow_id: %s", 
containers[0].flow_ctxs[0].flow_id);
+    if (containers[0].flow_ctxs[0].has_source_id)
+        FAIL("flow_map_id_pin: source_id should not be set");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_id_pin\n");
+    return 0;
+}
+
+static int test_flow_map_id_and_source_id(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34,"
+        "source_id=11111111-1111-1111-1111-111111111111";
+
+    ret = tams_parse_flow_map(str, 1, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_id_and_source_id: returned %d", ret);
+    if (!containers[0].flow_ctxs[0].has_flow_id ||
+        strcmp(containers[0].flow_ctxs[0].flow_id, 
"4f79cfd1-c057-47f4-8e4d-1b126ca7bf34"))
+        FAIL("flow_map_id_and_source_id: wrong flow_id");
+    if (!containers[0].flow_ctxs[0].has_source_id ||
+        strcmp(containers[0].flow_ctxs[0].source_id, 
"11111111-1111-1111-1111-111111111111"))
+        FAIL("flow_map_id_and_source_id: wrong source_id: %s",
+             containers[0].flow_ctxs[0].source_id);
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_id_and_source_id\n");
+    return 0;
+}
+
+static int test_flow_map_uppercase_ids(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,id=4F79CFD1-C057-47F4-8E4D-1B126CA7BF34,"
+        "source_id=AAAAAAAA-BBBB-4CCC-8DDD-EEEEEEEEEEEE,multi_flow=0 "
+        "flow=streams=1,multi_flow=0 "
+        "multi_flow=0,id=94996F2E-0CB5-43D3-AB6C-DB5A9CF667AA,"
+        "source_id=2AA143AC-0AB7-4D75-BC32-5C00C13D186F";
+
+    /* -flow_map UUIDs are forced to lower case as required by TAMS */
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_uppercase_ids: returned %d", ret);
+    if (strcmp(containers[0].flow_ctxs[0].flow_id, 
"4f79cfd1-c057-47f4-8e4d-1b126ca7bf34"))
+        FAIL("flow_map_uppercase_ids: wrong flow_id: %s", 
containers[0].flow_ctxs[0].flow_id);
+    if (strcmp(containers[0].flow_ctxs[0].source_id, 
"aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"))
+        FAIL("flow_map_uppercase_ids: wrong source_id: %s", 
containers[0].flow_ctxs[0].source_id);
+    if (strcmp(multis[0].flow_id, "94996f2e-0cb5-43d3-ab6c-db5a9cf667aa"))
+        FAIL("flow_map_uppercase_ids: wrong multi flow_id: %s", 
multis[0].flow_id);
+    if (strcmp(multis[0].source_id, "2aa143ac-0ab7-4d75-bc32-5c00c13d186f"))
+        FAIL("flow_map_uppercase_ids: wrong multi source_id: %s", 
multis[0].source_id);
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_uppercase_ids\n");
+    return 0;
+}
+
+static int test_flow_map_shared_container_requires_multi(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+
+    ret = tams_parse_flow_map("flow=streams=0,1,multi_flow=0", 2,
+                              &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_shared_container_requires_multi: returned %d", ret);
+    if (nb_containers != 1 || containers[0].nb_streams != 2)
+        FAIL("flow_map_shared_container_requires_multi: expected 1 container 
of 2 streams");
+    if (!containers[0].has_multi_flow || containers[0].multi_flow_index != 0)
+        FAIL("flow_map_shared_container_requires_multi: multi_flow not 
linked");
+    if (nb_multis != 1 || multis[0].index != 0 ||
+        multis[0].nb_container_indices != 1 || multis[0].container_indices[0] 
!= 0)
+        FAIL("flow_map_shared_container_requires_multi: multi cross-link 
wrong");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_shared_container_requires_multi\n");
+    return 0;
+}
+
+static int test_flow_map_shared_container_positional_ids(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,1,id=e85efab4-993b-4ad6-9af3-4cd8d0d38860,"
+        "id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34,multi_flow=0";
+
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_shared_container_positional_ids: returned %d", ret);
+    if (containers[0].nb_streams != 2)
+        FAIL("flow_map_shared_container_positional_ids: expected 2 flows in 
container");
+    if (!containers[0].flow_ctxs[0].has_flow_id ||
+        strcmp(containers[0].flow_ctxs[0].flow_id, 
"e85efab4-993b-4ad6-9af3-4cd8d0d38860"))
+        FAIL("flow_map_shared_container_positional_ids: flows[0] wrong: %s",
+             containers[0].flow_ctxs[0].flow_id);
+    if (!containers[0].flow_ctxs[1].has_flow_id ||
+        strcmp(containers[0].flow_ctxs[1].flow_id, 
"4f79cfd1-c057-47f4-8e4d-1b126ca7bf34"))
+        FAIL("flow_map_shared_container_positional_ids: flows[1] wrong: %s",
+             containers[0].flow_ctxs[1].flow_id);
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_shared_container_positional_ids\n");
+    return 0;
+}
+
+static int test_flow_map_shared_container_partial_id(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    /* only stream 0 gets an explicit id=; stream 1 is left for implicit 
resolution */
+    const char *str =
+        
"flow=streams=0,1,id=e85efab4-993b-4ad6-9af3-4cd8d0d38860,multi_flow=0";
+
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_shared_container_partial_id: returned %d", ret);
+    if (!containers[0].flow_ctxs[0].has_flow_id)
+        FAIL("flow_map_shared_container_partial_id: flows[0] should be 
pinned");
+    if (containers[0].flow_ctxs[1].has_flow_id)
+        FAIL("flow_map_shared_container_partial_id: flows[1] should be 
unpinned");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_shared_container_partial_id\n");
+    return 0;
+}
+
+static int test_flow_map_new_multi(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,multi_flow=0 "
+        "flow=streams=1,id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34,multi_flow=0";
+
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_new_multi: returned %d", ret);
+    if (nb_containers != 2 || nb_multis != 1)
+        FAIL("flow_map_new_multi: expected 2 containers/1 multi, got %d/%d",
+             nb_containers, nb_multis);
+    if (multis[0].has_flow_id || multis[0].has_source_id)
+        FAIL("flow_map_new_multi: multi should have no properties (fully 
new)");
+    if (multis[0].nb_container_indices != 2)
+        FAIL("flow_map_new_multi: expected both containers linked to the 
multi");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_new_multi\n");
+    return 0;
+}
+
+static int test_flow_map_existing_multi_property_token(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,multi_flow=0 flow=streams=1,multi_flow=0 "
+        "multi_flow=0,id=e85efab4-993b-4ad6-9af3-4cd8d0d38860";
+
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_existing_multi_property_token: returned %d", ret);
+    if (nb_multis != 1 || !multis[0].has_flow_id ||
+        strcmp(multis[0].flow_id, "e85efab4-993b-4ad6-9af3-4cd8d0d38860"))
+        FAIL("flow_map_existing_multi_property_token: wrong multi flow_id");
+    if (multis[0].nb_container_indices != 2)
+        FAIL("flow_map_existing_multi_property_token: expected 2 linked 
containers");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_existing_multi_property_token\n");
+    return 0;
+}
+
+static int test_flow_map_multi_source_id(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    const char *str =
+        "flow=streams=0,multi_flow=0 flow=streams=1,multi_flow=0 "
+        "multi_flow=0,source_id=11111111-1111-1111-1111-111111111111";
+
+    ret = tams_parse_flow_map(str, 2, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_multi_source_id: returned %d", ret);
+    if (!multis[0].has_source_id ||
+        strcmp(multis[0].source_id, "11111111-1111-1111-1111-111111111111"))
+        FAIL("flow_map_multi_source_id: wrong source_id: %s", 
multis[0].source_id);
+    if (multis[0].has_flow_id)
+        FAIL("flow_map_multi_source_id: flow_id should not be given");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_multi_source_id\n");
+    return 0;
+}
+
+static int test_flow_map_two_independent_multis(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    /* two separate multi-Flow groupings in one invocation */
+    const char *str =
+        "flow=streams=0,multi_flow=0 flow=streams=1,multi_flow=0 "
+        "flow=streams=2,multi_flow=1 flow=streams=3,multi_flow=1 "
+        "multi_flow=0,id=aaaaaaaa-0000-0000-0000-000000000000 "
+        "multi_flow=1,id=bbbbbbbb-0000-0000-0000-000000000000";
+
+    ret = tams_parse_flow_map(str, 4, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_two_independent_multis: returned %d", ret);
+    if (nb_containers != 4 || nb_multis != 2)
+        FAIL("flow_map_two_independent_multis: expected 4 containers/2 multis, 
got %d/%d",
+             nb_containers, nb_multis);
+    if (!multis[0].has_flow_id ||
+        strcmp(multis[0].flow_id, "aaaaaaaa-0000-0000-0000-000000000000"))
+        FAIL("flow_map_two_independent_multis: multi[0] wrong");
+    if (!multis[1].has_flow_id ||
+        strcmp(multis[1].flow_id, "bbbbbbbb-0000-0000-0000-000000000000"))
+        FAIL("flow_map_two_independent_multis: multi[1] wrong");
+    if (multis[0].nb_container_indices != 2 || multis[1].nb_container_indices 
!= 2)
+        FAIL("flow_map_two_independent_multis: wrong container linkage 
counts");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_two_independent_multis\n");
+    return 0;
+}
+
+static int test_flow_map_standalone_and_grouped_mixed(void)
+{
+    TAMSContainerContext *containers;
+    TAMSMultiFlowContext *multis;
+    int nb_containers, nb_multis, ret;
+    /* stream 0 fully standalone, streams 1+2 grouped under a new multi */
+    const char *str =
+        "flow=streams=0 flow=streams=1,multi_flow=0 
flow=streams=2,multi_flow=0";
+
+    ret = tams_parse_flow_map(str, 3, &containers, &nb_containers, &multis, 
&nb_multis);
+    if (ret < 0)
+        FAIL("flow_map_standalone_and_grouped_mixed: returned %d", ret);
+    if (nb_containers != 3 || nb_multis != 1)
+        FAIL("flow_map_standalone_and_grouped_mixed: expected 3 containers/1 
multi");
+    if (containers[0].has_multi_flow)
+        FAIL("flow_map_standalone_and_grouped_mixed: container 0 should be 
standalone");
+    if (!containers[1].has_multi_flow || !containers[2].has_multi_flow)
+        FAIL("flow_map_standalone_and_grouped_mixed: containers 1/2 should be 
grouped");
+
+    free_result(containers, nb_containers, multis, nb_multis);
+    printf("OK: flow_map_standalone_and_grouped_mixed\n");
+    return 0;
+}
+
+/* ====================================================================
+ * UUID tests
+ * ==================================================================== */
+
+static int test_is_valid_uuid(void)
+{
+    if (!tams_is_valid_uuid("11111111-2222-3333-4444-555555555555"))
+        FAIL("is_valid_uuid: canonical lowercase UUID should be valid");
+    if (!tams_is_valid_uuid("AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"))
+        FAIL("is_valid_uuid: uppercase UUID should be valid");
+    if (tams_is_valid_uuid("not-a-uuid"))
+        FAIL("is_valid_uuid: garbage should be invalid");
+    if (tams_is_valid_uuid("11111111-2222-3333-4444-55555555555"))
+        FAIL("is_valid_uuid: too short should be invalid");
+    if (tams_is_valid_uuid("11111111x2222-3333-4444-555555555555"))
+        FAIL("is_valid_uuid: wrong separator should be invalid");
+
+    printf("OK: is_valid_uuid\n");
+    return 0;
+}
+
+/* ====================================================================
+ * Default muxer tests
+ * ==================================================================== */
+
+/* Every default raw-ES muxer's codec needs a MIME type, which names its 
container */
+static int test_default_muxers_have_mime(void)
+{
+    for (int i = 0; i < FF_ARRAY_ELEMS(tams_default_muxers); i++)
+        if (!ff_tams_mime_from_codec(tams_default_muxers[i].codec_id))
+            FAIL("default_muxers_have_mime: %s has no MIME type",
+                 avcodec_get_name(tams_default_muxers[i].codec_id));
+
+    printf("OK: default_muxers_have_mime\n");
+    return 0;
+}
+
+/* ====================================================================
+ * Container mapping tests
+ * ==================================================================== */
+
+/*
+ * Setup: A shared container holds video, audio and audio streams.
+ * Expected: format_track_index counts within each media type: 0, 0, 1.
+ */
+static int test_format_track_index(void)
+{
+    static const enum AVMediaType types[] = {
+        AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_AUDIO,
+    };
+    static const int expected[] = { 0, 0, 1 };
+    AVFormatContext *s = avformat_alloc_context();
+    int stream_indices[] = { 0, 1, 2 };
+    TAMSContainerContext cc = { .stream_indices = stream_indices, .nb_streams 
= 3 };
+
+    if (!s)
+        FAIL("format_track_index: alloc_context failed");
+    for (int i = 0; i < 3; i++) {
+        AVStream *st = avformat_new_stream(s, NULL);
+        if (!st) {
+            avformat_free_context(s);
+            FAIL("format_track_index: new_stream failed");
+        }
+        st->codecpar->codec_type = types[i];
+    }
+
+    for (int k = 0; k < 3; k++) {
+        int index = tams_format_track_index(s, &cc, k);
+        if (index != expected[k]) {
+            avformat_free_context(s);
+            FAIL("format_track_index: stream %d got %d, expected %d", k, 
index, expected[k]);
+        }
+    }
+
+    avformat_free_context(s);
+    printf("OK: format_track_index\n");
+    return 0;
+}
+
+/* ====================================================================
+ * Init tests
+ * ==================================================================== */
+
+static int test_init_missing_multi_flow_fails(void)
+{
+    AVFormatContext *s = avformat_alloc_context();
+    TAMSMuxContext *c;
+    int ret;
+
+    if (!s)
+        FAIL("init_missing_multi_flow: alloc_context failed");
+
+    s->oformat = &ff_tams_muxer.p;
+    if (avformat_new_stream(s, NULL) == NULL ||
+        avformat_new_stream(s, NULL) == NULL) {
+        avformat_free_context(s);
+        FAIL("init_missing_multi_flow: new_stream failed");
+    }
+
+    s->priv_data = av_mallocz(sizeof(TAMSMuxContext));
+    if (!s->priv_data) {
+        avformat_free_context(s);
+        FAIL("init_missing_multi_flow: priv_data alloc failed");
+    }
+    c = s->priv_data;
+    c->class = &tams_muxer_class;
+    av_opt_set_defaults(c);
+
+    /* two streams sharing one container, but no multi_flow= given: invalid */
+    c->flow_map_str = av_strdup("flow=streams=0,1");
+
+    ret = tams_init(s);
+    if (ret >= 0) {
+        tams_deinit(s);
+        av_freep(&c->flow_map_str);
+        av_freep(&s->priv_data);
+        avformat_free_context(s);
+        FAIL("init_missing_multi_flow: expected failure but got success");
+    }
+
+    tams_deinit(s);
+    av_freep(&c->flow_map_str);
+    av_freep(&s->priv_data);
+    avformat_free_context(s);
+
+    printf("OK: init_missing_multi_flow_fails (correctly failed with %d)\n", 
ret);
+    return 0;
+}
+
+/* ====================================================================
+ * Main
+ * ==================================================================== */
+
+int main(int argc, char *argv[])
+{
+    int ret = 0;
+
+    ret |= test_flow_map_default();
+    ret |= test_flow_map_empty_string();
+    ret |= test_flow_map_explicit_split();
+    ret |= test_flow_map_unmentioned_stream_gets_default();
+    ret |= test_flow_map_id_pin();
+    ret |= test_flow_map_id_and_source_id();
+    ret |= test_flow_map_uppercase_ids();
+
+    ret |= test_flow_map_shared_container_requires_multi();
+    ret |= test_flow_map_shared_container_positional_ids();
+    ret |= test_flow_map_shared_container_partial_id();
+
+    ret |= test_flow_map_new_multi();
+    ret |= test_flow_map_existing_multi_property_token();
+    ret |= test_flow_map_multi_source_id();
+    ret |= test_flow_map_two_independent_multis();
+    ret |= test_flow_map_standalone_and_grouped_mixed();
+
+    ret |= test_is_valid_uuid();
+    ret |= test_default_muxers_have_mime();
+    ret |= test_format_track_index();
+    ret |= test_init_missing_multi_flow_fails();
+
+    printf("#### The following should fail ####\n");
+    ret |= test_flow_map_fails("flow_map_bad_token", "foo=streams=0", 1);
+    ret |= test_flow_map_fails("flow_map_out_of_range", "flow=streams=5", 2);
+    ret |= test_flow_map_fails("flow_map_duplicate_assignment",
+                                "flow=streams=0 flow=streams=0", 2);
+    ret |= test_flow_map_fails("flow_map_empty_list", "flow=streams=", 2);
+    ret |= test_flow_map_fails("flow_map_malformed_index", "flow=streams=abc", 
2);
+    ret |= test_flow_map_fails("flow_map_shared_container_missing_multi",
+                                "flow=streams=0,1", 2);
+    ret |= test_flow_map_fails("flow_map_too_many_ids",
+                                
"flow=streams=0,id=e85efab4-993b-4ad6-9af3-4cd8d0d38860,"
+                                "id=4f79cfd1-c057-47f4-8e4d-1b126ca7bf34", 1);
+    ret |= test_flow_map_fails("flow_map_bad_uuid",
+                                "flow=streams=0,id=not-a-uuid", 1);
+    ret |= test_flow_map_fails("flow_map_duplicate_source_id",
+                                
"flow=streams=0,source_id=11111111-1111-1111-1111-111111111111,"
+                                
"source_id=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", 1);
+    ret |= test_flow_map_fails("flow_map_duplicate_multi_flow_attr",
+                                "flow=streams=0,multi_flow=0,multi_flow=1", 1);
+    ret |= test_flow_map_fails("flow_map_unknown_attr",
+                                "flow=streams=0,bogus=1", 1);
+    ret |= test_flow_map_fails("flow_map_multi_no_attrs", "multi_flow=0", 1);
+    ret |= test_flow_map_fails("flow_map_multi_duplicate_index",
+                                "flow=streams=0,multi_flow=0 
flow=streams=1,multi_flow=0 "
+                                
"multi_flow=0,id=aaaaaaaa-0000-0000-0000-000000000000 "
+                                
"multi_flow=0,id=bbbbbbbb-0000-0000-0000-000000000000", 2);
+    ret |= test_flow_map_fails("flow_map_orphan_multi_flow_token",
+                                "flow=streams=0 "
+                                
"multi_flow=0,id=aaaaaaaa-0000-0000-0000-000000000000", 1);
+    printf("#### End failing tests ####\n");
+
+    if (ret)
+        printf("\nSOME TESTS FAILED\n");
+    else
+        printf("\nALL TESTS PASSED\n");
+
+    return ret;
+}
diff --git a/libavformat/version.h b/libavformat/version.h
index d8fc959f19b..a8385d1a7bd 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -31,7 +31,7 @@
 
 #include "version_major.h"
 
-#define LIBAVFORMAT_VERSION_MINOR  22
+#define LIBAVFORMAT_VERSION_MINOR  23
 #define LIBAVFORMAT_VERSION_MICRO 100
 
 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \
diff --git a/tests/fate/libavformat.mak b/tests/fate/libavformat.mak
index 1ada4ee4ad1..427c4866ab2 100644
--- a/tests/fate/libavformat.mak
+++ b/tests/fate/libavformat.mak
@@ -113,6 +113,10 @@ FATE_LIBAVFORMAT-$(CONFIG_TAMS_DEMUXER) += fate-tamsdec
 fate-tamsdec: libavformat/tests/tamsdec$(EXESUF)
 fate-tamsdec: CMD = run libavformat/tests/tamsdec$(EXESUF)
 
+FATE_LIBAVFORMAT-$(CONFIG_TAMS_MUXER) += fate-tamsenc
+fate-tamsenc: libavformat/tests/tamsenc$(EXESUF)
+fate-tamsenc: CMD = run libavformat/tests/tamsenc$(EXESUF)
+
 FATE_LIBAVFORMAT += fate-seek_utils
 fate-seek_utils: libavformat/tests/seek_utils$(EXESUF)
 fate-seek_utils: CMD = run libavformat/tests/seek_utils$(EXESUF)
diff --git a/tests/ref/fate/tamsenc b/tests/ref/fate/tamsenc
new file mode 100644
index 00000000000..504ccc94cf9
--- /dev/null
+++ b/tests/ref/fate/tamsenc
@@ -0,0 +1,37 @@
+OK: flow_map_default
+OK: flow_map_empty_string
+OK: flow_map_explicit_split
+OK: flow_map_unmentioned_stream_gets_default
+OK: flow_map_id_pin
+OK: flow_map_id_and_source_id
+OK: flow_map_uppercase_ids
+OK: flow_map_shared_container_requires_multi
+OK: flow_map_shared_container_positional_ids
+OK: flow_map_shared_container_partial_id
+OK: flow_map_new_multi
+OK: flow_map_existing_multi_property_token
+OK: flow_map_multi_source_id
+OK: flow_map_two_independent_multis
+OK: flow_map_standalone_and_grouped_mixed
+OK: is_valid_uuid
+OK: default_muxers_have_mime
+OK: format_track_index
+OK: init_missing_multi_flow_fails (correctly failed with -22)
+#### The following should fail ####
+OK: flow_map_bad_token (correctly failed with -22)
+OK: flow_map_out_of_range (correctly failed with -22)
+OK: flow_map_duplicate_assignment (correctly failed with -22)
+OK: flow_map_empty_list (correctly failed with -22)
+OK: flow_map_malformed_index (correctly failed with -22)
+OK: flow_map_shared_container_missing_multi (correctly failed with -22)
+OK: flow_map_too_many_ids (correctly failed with -22)
+OK: flow_map_bad_uuid (correctly failed with -22)
+OK: flow_map_duplicate_source_id (correctly failed with -22)
+OK: flow_map_duplicate_multi_flow_attr (correctly failed with -22)
+OK: flow_map_unknown_attr (correctly failed with -22)
+OK: flow_map_multi_no_attrs (correctly failed with -22)
+OK: flow_map_multi_duplicate_index (correctly failed with -22)
+OK: flow_map_orphan_multi_flow_token (correctly failed with -22)
+#### End failing tests ####
+
+ALL TESTS PASSED
-- 
2.43.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to