PR #26281 opened by Romain Beauxis (toots)
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26281
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26281.patch

The Ogg demuxer keeps its codec-specific code in one file per codec, behind 
`struct ogg_codec`. The muxer has no such split: its generic paging code checks 
the codec ID 31 times. This PR moves that code out of the muxer into one 
mapping per codec, `OGGMuxerMapping`, in `ogg/muxer/<codec>.c`. `muxer.c` goes 
from 1039 to 725 lines, and the mapping lookup is the only codec ID check it 
keeps.

This is a reorganisation with no functional change. The two small 
implementation changes the split needs each have their own commit, before any 
code moves. So the review can focus on structure: file layout, naming, symbol 
visibility and build integration. Each codec file exports only its 
`ff_ogg_<codec>_muxer_mapping`, and the shared helpers are `static inline` in 
`ogg/muxer.h`. Muxing behaviour only needs checking for a regression the tests 
below would have missed, and such a regression would bisect to a single commit.

Commits:

- `avformat/ogg/mapping: move to ogg/demuxer/`: pure rename of the demuxer 
mappings and their header, to sit next to `ogg/muxer/`.
- `avformat/ogg/muxer: move the comment header writer to the muxer header`: 
makes the VorbisComment packet writer shared by every codec a `static inline` 
in the new `ogg/muxer.h`.
- `avformat/ogg/muxer: copy the Vorbis and Theora header packets`: copies those 
headers out of the extradata, so every stream owns its header packets and 
cleanup no longer depends on the codec.
- `avformat/ogg/muxer: flush the pages of every video stream on keyframes`: 
selects the keyframe and timestamp-jump page flush by media type instead of the 
Theora/VP8 codec check.
- `avformat/ogg/muxer: describe the codecs with muxer mappings`: replaces the 
codec ID checks with `OGGMuxerMapping` callbacks, still inside `muxer.c`. The 
callbacks cover header building, granules, keyframes and new links.
- `avformat/ogg/muxer: move the codec mappings to ogg/muxer/`: moves each 
mapping to its own file, with static functions named `<codec>_<role>` as in the 
demuxer.

Testing, at every commit:

- Each commit builds on its own, `make checkheaders` passes, and the 144 
Ogg-related FATE tests pass with no ref changes.
- Remuxing 17 cases (every codec, chained links, chapters, metadata, 
`page_duration`, `serial_offset`, the missing-extradata error) produces output 
byte-identical to master's, with identical error logs.
- macOS `leaks` reports no leak when muxing Vorbis, Theora, VP8, Speex, Opus 
and FLAC.


>From a3c4d2c9f0814872de69a86dfa162580d2b2b5ef Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:14:01 -0500
Subject: [PATCH 1/6] avformat/ogg/mapping: move to ogg/demuxer/

The codec mappings in ogg/mapping/ are the demuxer's. Name their
directory and header after it, so the muxer's mappings can sit next to
them in ogg/muxer/.
---
 MAINTAINERS                                   |  4 ++--
 doc/developer.texi                            |  7 ++++---
 libavformat/ogg/Makefile                      | 20 +++++++++----------
 libavformat/ogg/demuxer.c                     |  2 +-
 libavformat/ogg/{mapping.h => demuxer.h}      |  6 +++---
 libavformat/ogg/{mapping => demuxer}/dirac.c  |  2 +-
 libavformat/ogg/{mapping => demuxer}/flac.c   |  2 +-
 libavformat/ogg/{mapping => demuxer}/ogm.c    |  2 +-
 libavformat/ogg/{mapping => demuxer}/opus.c   |  2 +-
 .../ogg/{mapping => demuxer}/skeleton.c       |  2 +-
 libavformat/ogg/{mapping => demuxer}/speex.c  |  2 +-
 libavformat/ogg/{mapping => demuxer}/theora.c |  2 +-
 libavformat/ogg/{mapping => demuxer}/vorbis.c |  2 +-
 libavformat/ogg/{mapping => demuxer}/vp8.c    |  2 +-
 14 files changed, 29 insertions(+), 28 deletions(-)
 rename libavformat/ogg/{mapping.h => demuxer.h} (98%)
 rename libavformat/ogg/{mapping => demuxer}/dirac.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/flac.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/ogm.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/opus.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/skeleton.c (98%)
 rename libavformat/ogg/{mapping => demuxer}/speex.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/theora.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/vorbis.c (99%)
 rename libavformat/ogg/{mapping => demuxer}/vp8.c (99%)

diff --git a/MAINTAINERS b/MAINTAINERS
index 1269d5833e6..60c0fc62457 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -470,9 +470,9 @@ Muxers/Demuxers:
   nsvdec.c                              Francois Revol
   nut*                                  Michael Niedermayer
   nuv.c                                 Reimar Doeffinger
-  ogg/demuxer.c, ogg/mapping.h          David Conrad, Romain Beauxis
+  ogg/demuxer.c, ogg/demuxer.h          David Conrad, Romain Beauxis
   ogg/muxer.c                           Baptiste Coudurier, Romain Beauxis
-  ogg/mapping/*                         David Conrad, Romain Beauxis
+  ogg/demuxer/*                         David Conrad, Romain Beauxis
   oma.c                                 Maxim Poliakovski
   pp_bnk.c                              Zane van Iperen
   psxstr.c                              Mike Melanson
diff --git a/doc/developer.texi b/doc/developer.texi
index 5ab6dbee819..b9c7a0acb27 100644
--- a/doc/developer.texi
+++ b/doc/developer.texi
@@ -394,7 +394,8 @@ feature, for example Ogg or ID3v2.
 A subsystem made of more than one file lives in its own directory inside its
 library, for example @file{libavformat/ogg/}.
 A nested directory groups related files within a subsystem, for example the
-per-codec mappings (@code{struct ogg_codec}) in 
@file{libavformat/ogg/mapping/}.
+per-codec mappings of the demuxer (@code{struct ogg_codec}) in
+@file{libavformat/ogg/demuxer/}.
 
 @subsection File names
 
@@ -418,9 +419,9 @@ Files that predate these rules keep their names until a 
commit moves them.
 @subsection Includes
 
 A file includes headers from its own directory by their bare name, for example
-@code{#include "mapping.h"}.
+@code{#include "demuxer.h"}.
 It includes all other headers by their path from the source root, for example
-@code{#include "libavformat/ogg/mapping.h"}.
+@code{#include "libavformat/ogg/demuxer.h"}.
 The include path then names the group each header belongs to.
 
 @subsection Build system
diff --git a/libavformat/ogg/Makefile b/libavformat/ogg/Makefile
index 5d75953a79d..b1e41c54a1d 100644
--- a/libavformat/ogg/Makefile
+++ b/libavformat/ogg/Makefile
@@ -2,19 +2,19 @@ HEADER_DIRS += ogg
 
 clean::
        $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/%)
-       $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/mapping/%)
+       $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/demuxer/%)
 
 OBJS-$(CONFIG_OGG_DEMUXER) +=  \
     ogg/demuxer.o              \
-    ogg/mapping/dirac.o        \
-    ogg/mapping/flac.o         \
-    ogg/mapping/ogm.o          \
-    ogg/mapping/opus.o         \
-    ogg/mapping/skeleton.o     \
-    ogg/mapping/speex.o        \
-    ogg/mapping/theora.o       \
-    ogg/mapping/vorbis.o       \
-    ogg/mapping/vp8.o          \
+    ogg/demuxer/dirac.o        \
+    ogg/demuxer/flac.o         \
+    ogg/demuxer/ogm.o          \
+    ogg/demuxer/opus.o         \
+    ogg/demuxer/skeleton.o     \
+    ogg/demuxer/speex.o        \
+    ogg/demuxer/theora.o       \
+    ogg/demuxer/vorbis.o       \
+    ogg/demuxer/vp8.o          \
 
 OBJS-$(CONFIG_OGA_MUXER)   += ogg/muxer.o
 OBJS-$(CONFIG_OGG_MUXER)   += ogg/muxer.o
diff --git a/libavformat/ogg/demuxer.c b/libavformat/ogg/demuxer.c
index 015f0e1b9c8..c6c8dcc693d 100644
--- a/libavformat/ogg/demuxer.c
+++ b/libavformat/ogg/demuxer.c
@@ -34,7 +34,7 @@
 #include "libavutil/mem.h"
 #include "libavformat/avio_internal.h"
 #include "libavformat/demux.h"
-#include "mapping.h"
+#include "demuxer.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
 
diff --git a/libavformat/ogg/mapping.h b/libavformat/ogg/demuxer.h
similarity index 98%
rename from libavformat/ogg/mapping.h
rename to libavformat/ogg/demuxer.h
index eed10aaa98d..ac44c32911f 100644
--- a/libavformat/ogg/mapping.h
+++ b/libavformat/ogg/demuxer.h
@@ -22,8 +22,8 @@
     DEALINGS IN THE SOFTWARE.
 **/
 
-#ifndef AVFORMAT_OGG_MAPPING_H
-#define AVFORMAT_OGG_MAPPING_H
+#ifndef AVFORMAT_OGG_DEMUXER_H
+#define AVFORMAT_OGG_DEMUXER_H
 
 #include "libavformat/avformat.h"
 
@@ -188,4 +188,4 @@ ogg_gptopts (AVFormatContext * s, int i, uint64_t gp, 
int64_t *dts)
     return pts;
 }
 
-#endif /* AVFORMAT_OGG_MAPPING_H */
+#endif /* AVFORMAT_OGG_DEMUXER_H */
diff --git a/libavformat/ogg/mapping/dirac.c b/libavformat/ogg/demuxer/dirac.c
similarity index 99%
rename from libavformat/ogg/mapping/dirac.c
rename to libavformat/ogg/demuxer/dirac.c
index 7b6523ac055..3fadb6e8072 100644
--- a/libavformat/ogg/mapping/dirac.c
+++ b/libavformat/ogg/demuxer/dirac.c
@@ -24,7 +24,7 @@
 #include "libavcodec/dirac.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 
 static int dirac_header(AVFormatContext *s, int idx)
 {
diff --git a/libavformat/ogg/mapping/flac.c b/libavformat/ogg/demuxer/flac.c
similarity index 99%
rename from libavformat/ogg/mapping/flac.c
rename to libavformat/ogg/demuxer/flac.c
index a9c0317a9b9..c0b0e059f18 100644
--- a/libavformat/ogg/mapping/flac.c
+++ b/libavformat/ogg/demuxer/flac.c
@@ -25,7 +25,7 @@
 #include "libavcodec/flac.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 
 #define OGG_FLAC_METADATA_TYPE_STREAMINFO 0x7F
diff --git a/libavformat/ogg/mapping/ogm.c b/libavformat/ogg/demuxer/ogm.c
similarity index 99%
rename from libavformat/ogg/mapping/ogm.c
rename to libavformat/ogg/demuxer/ogm.c
index 1db2268ea0f..b7110f8a3f1 100644
--- a/libavformat/ogg/mapping/ogm.c
+++ b/libavformat/ogg/demuxer/ogm.c
@@ -30,7 +30,7 @@
 
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 #include "libavformat/riff.h"
 
diff --git a/libavformat/ogg/mapping/opus.c b/libavformat/ogg/demuxer/opus.c
similarity index 99%
rename from libavformat/ogg/mapping/opus.c
rename to libavformat/ogg/demuxer/opus.c
index 714c4709b65..0b09552c7c6 100644
--- a/libavformat/ogg/mapping/opus.c
+++ b/libavformat/ogg/demuxer/opus.c
@@ -26,7 +26,7 @@
 #include "libavcodec/opus/tab.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 
 struct oggopus_private {
diff --git a/libavformat/ogg/mapping/skeleton.c 
b/libavformat/ogg/demuxer/skeleton.c
similarity index 98%
rename from libavformat/ogg/mapping/skeleton.c
rename to libavformat/ogg/demuxer/skeleton.c
index 53eb176f98d..9624b5f173a 100644
--- a/libavformat/ogg/mapping/skeleton.c
+++ b/libavformat/ogg/demuxer/skeleton.c
@@ -21,7 +21,7 @@
 #include "libavutil/intreadwrite.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 
 static int skeleton_header(AVFormatContext *s, int idx)
 {
diff --git a/libavformat/ogg/mapping/speex.c b/libavformat/ogg/demuxer/speex.c
similarity index 99%
rename from libavformat/ogg/mapping/speex.c
rename to libavformat/ogg/demuxer/speex.c
index f15d3e50d07..3beefac84d8 100644
--- a/libavformat/ogg/mapping/speex.c
+++ b/libavformat/ogg/demuxer/speex.c
@@ -28,7 +28,7 @@
 
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 
 struct speex_params {
diff --git a/libavformat/ogg/mapping/theora.c b/libavformat/ogg/demuxer/theora.c
similarity index 99%
rename from libavformat/ogg/mapping/theora.c
rename to libavformat/ogg/demuxer/theora.c
index 58de1fcf1d8..4fd66541bbe 100644
--- a/libavformat/ogg/mapping/theora.c
+++ b/libavformat/ogg/demuxer/theora.c
@@ -28,7 +28,7 @@
 #include "libavcodec/get_bits.h"
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 
 enum TheoraPacketType {
diff --git a/libavformat/ogg/mapping/vorbis.c b/libavformat/ogg/demuxer/vorbis.c
similarity index 99%
rename from libavformat/ogg/mapping/vorbis.c
rename to libavformat/ogg/demuxer/vorbis.c
index e3380d665af..fd5b26fbd31 100644
--- a/libavformat/ogg/mapping/vorbis.c
+++ b/libavformat/ogg/demuxer/vorbis.c
@@ -33,7 +33,7 @@
 #include "libavformat/avformat.h"
 #include "libavformat/demux.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 #include "libavformat/replaygain.h"
 
diff --git a/libavformat/ogg/mapping/vp8.c b/libavformat/ogg/demuxer/vp8.c
similarity index 99%
rename from libavformat/ogg/mapping/vp8.c
rename to libavformat/ogg/demuxer/vp8.c
index 0bf22bb03db..9b5569e075d 100644
--- a/libavformat/ogg/mapping/vp8.c
+++ b/libavformat/ogg/demuxer/vp8.c
@@ -23,7 +23,7 @@
 
 #include "libavformat/avformat.h"
 #include "libavformat/internal.h"
-#include "libavformat/ogg/mapping.h"
+#include "libavformat/ogg/demuxer.h"
 #include "libavformat/vorbis/comment.h"
 
 #define VP8_HEADER_SIZE 26
-- 
2.54.1


>From db3a346db6aa88f248eeb90b3b408a26e82b62ae Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:09:17 -0500
Subject: [PATCH 2/6] avformat/ogg/muxer: move the comment header writer to the
 muxer header

The comment header of each codec is the same VorbisComment packet, with
room for the codec's packet type in front. Move its writer to a header
so the codec mappings of the muxer can share it.
---
 libavformat/ogg/muxer.c | 31 +----------------
 libavformat/ogg/muxer.h | 75 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 76 insertions(+), 30 deletions(-)
 create mode 100644 libavformat/ogg/muxer.h

diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index 69b9a679b9b..a05afa4b084 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -38,6 +38,7 @@
 #include "libavformat/mux.h"
 #include "libavformat/version.h"
 #include "libavformat/vorbis/comment.h"
+#include "muxer.h"
 
 #define MAX_PAGE_SIZE 65025
 
@@ -297,36 +298,6 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream 
*st,
     return 0;
 }
 
-static uint8_t *ogg_write_vorbiscomment(int64_t offset, int bitexact,
-                                        int *header_len, AVDictionary **m, int 
framing_bit,
-                                        AVChapter **chapters, unsigned int 
nb_chapters)
-{
-    const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
-    FFIOContext pb;
-    int64_t size;
-    uint8_t *p;
-
-    ff_metadata_conv(m, ff_vorbis_comment_metadata_conv, NULL);
-
-    size = ff_vorbis_comment_length(*m, vendor, chapters, nb_chapters);
-    if (size < 0)
-        return NULL;
-    size += offset + framing_bit;
-    if (size > INT_MAX)
-        return NULL;
-    p = av_mallocz(size);
-    if (!p)
-        return NULL;
-
-    ffio_init_write_context(&pb, p + offset, size - offset);
-    ff_vorbis_comment_write(&pb.pub, *m, vendor, chapters, nb_chapters);
-    if (framing_bit)
-        avio_w8(&pb.pub, 1);
-
-    *header_len = size;
-    return p;
-}
-
 static int ogg_build_flac_headers(AVCodecParameters *par,
                                   OGGStreamContext *oggstream, int bitexact,
                                   AVDictionary **m)
diff --git a/libavformat/ogg/muxer.h b/libavformat/ogg/muxer.h
new file mode 100644
index 00000000000..a759cb136dc
--- /dev/null
+++ b/libavformat/ogg/muxer.h
@@ -0,0 +1,75 @@
+/*
+ * Ogg muxer
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#ifndef AVFORMAT_OGG_MUXER_H
+#define AVFORMAT_OGG_MUXER_H
+
+#include <stdint.h>
+
+#include "libavutil/dict.h"
+#include "libavutil/mem.h"
+#include "libavformat/avformat.h"
+#include "libavformat/avio_internal.h"
+#include "libavformat/metadata.h"
+#include "libavformat/version.h"
+#include "libavformat/vorbis/comment.h"
+
+/**
+ * Allocate a comment header packet holding a VorbisComment. The metadata is
+ * converted to VorbisComment field names in place.
+ *
+ * @param offset      the number of zeroed bytes before the VorbisComment, left
+ *                    for the codec's packet type
+ * @param header_len  set to the packet size
+ * @param framing_bit whether the packet ends with a framing bit
+ * @return the packet, to free with av_free(), or NULL on error
+ */
+static inline uint8_t *ogg_write_vorbiscomment(int64_t offset, int bitexact,
+                                               int *header_len, AVDictionary 
**m, int framing_bit,
+                                               AVChapter **chapters, unsigned 
int nb_chapters)
+{
+    const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
+    FFIOContext pb;
+    int64_t size;
+    uint8_t *p;
+
+    ff_metadata_conv(m, ff_vorbis_comment_metadata_conv, NULL);
+
+    size = ff_vorbis_comment_length(*m, vendor, chapters, nb_chapters);
+    if (size < 0)
+        return NULL;
+    size += offset + framing_bit;
+    if (size > INT_MAX)
+        return NULL;
+    p = av_mallocz(size);
+    if (!p)
+        return NULL;
+
+    ffio_init_write_context(&pb, p + offset, size - offset);
+    ff_vorbis_comment_write(&pb.pub, *m, vendor, chapters, nb_chapters);
+    if (framing_bit)
+        avio_w8(&pb.pub, 1);
+
+    *header_len = size;
+    return p;
+}
+
+#endif /* AVFORMAT_OGG_MUXER_H */
-- 
2.54.1


>From 2b839a436f100d201eec636721db723c425ff0e8 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:31:26 -0500
Subject: [PATCH 3/6] avformat/ogg/muxer: copy the Vorbis and Theora header
 packets

The identification and setup headers of Vorbis and Theora point into
the extradata, while those of the other codecs are allocated, so freeing
them depends on the codec. Copy them out of the extradata, so that a
stream owns all of its header packets.
---
 libavformat/ogg/muxer.c | 19 +++++++++----------
 1 file changed, 9 insertions(+), 10 deletions(-)

diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index a05afa4b084..683a83121b6 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -109,14 +109,8 @@ static void ogg_cleanup_stream(AVStream *st)
 {
     OGGStreamContext *oggstream = st->priv_data;
 
-    if (st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
-        st->codecpar->codec_id == AV_CODEC_ID_SPEEX ||
-        st->codecpar->codec_id == AV_CODEC_ID_OPUS ||
-        st->codecpar->codec_id == AV_CODEC_ID_VP8) {
-        av_freep(&oggstream->header[0]);
-    }
-
-    av_freep(&oggstream->header[1]);
+    for (int i = 0; i < 3; i++)
+        av_freep(&oggstream->header[i]);
 }
 
 static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
@@ -574,6 +568,7 @@ static int ogg_init(AVFormatContext *s)
                 return err;
             }
         } else {
+            const uint8_t *header[3];
             uint8_t *p;
             const char *cstr = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 
"vorbis" : "theora";
             int header_type = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 3 
: 0x81;
@@ -581,12 +576,16 @@ static int ogg_init(AVFormatContext *s)
 
             if (avpriv_split_xiph_headers(st->codecpar->extradata, 
st->codecpar->extradata_size,
                                       st->codecpar->codec_id == 
AV_CODEC_ID_VORBIS ? 30 : 42,
-                                      (const uint8_t**)oggstream->header, 
oggstream->header_len) < 0) {
+                                      header, oggstream->header_len) < 0) {
                 av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
-                oggstream->header[1] = NULL;
                 return AVERROR_INVALIDDATA;
             }
 
+            oggstream->header[0] = av_memdup(header[0], 
oggstream->header_len[0]);
+            oggstream->header[2] = av_memdup(header[2], 
oggstream->header_len[2]);
+            if (!oggstream->header[0] || !oggstream->header[2])
+                return AVERROR(ENOMEM);
+
             p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
                                         &oggstream->header_len[1], 
&st->metadata,
                                         framing_bit, NULL, 0);
-- 
2.54.1


>From e82d2c8a19fe8d30eb4c4bf78dcc86ed3f92a948 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:31:43 -0500
Subject: [PATCH 4/6] avformat/ogg/muxer: flush the pages of every video stream
 on keyframes

Theora and VP8, the only video codecs the muxer supports, end a page on
keyframes and timestamp jumps. Select that by the media type rather than
by codec, so that it does not depend on a codec list.
---
 libavformat/ogg/muxer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index 683a83121b6..f830f5e371f 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -225,7 +225,7 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
     // them as such, otherwise seeking will not work correctly at the very
     // least with old libogg versions.
     // Do not try to flush header packets though, that will create broken 
files.
-    if ((st->codecpar->codec_id == AV_CODEC_ID_THEORA || 
st->codecpar->codec_id == AV_CODEC_ID_VP8) && !header &&
+    if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !header &&
         (ogg_granule_to_timestamp(oggstream, granule) >
          ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
          ogg_key_granule(oggstream, granule))) {
-- 
2.54.1


>From 68701558e1ed784818afbe2edcebe3be361a3cd1 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:10:12 -0500
Subject: [PATCH 5/6] avformat/ogg/muxer: describe the codecs with muxer
 mappings

The codec-specific parts of the muxer are spread over its generic code
as checks on the codec ID. Gather them per codec in an OGGMuxerMapping:
header building, granule computation and conversion, keyframe granules
and new link support. Theora keeps its granule state in the mapping's
private data.
---
 libavformat/ogg/muxer.c | 530 +++++++++++++++++++++++++++-------------
 1 file changed, 361 insertions(+), 169 deletions(-)

diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index f830f5e371f..ffd16b5a63f 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -53,16 +53,14 @@ typedef struct OGGPage {
     uint16_t size;
 } OGGPage;
 
+typedef struct OGGMuxerMapping OGGMuxerMapping;
+
 typedef struct OGGStreamContext {
     unsigned page_counter;
     uint8_t *header[3];
     int header_len[3];
-    /** for theora granule */
-    int kfgshift;
-    int64_t last_kf_pts;
-    int vrev;
-    /* for VP8 granule */
-    int isvp8;
+    const OGGMuxerMapping *mapping;
+    void *priv_data; ///< state of the mapping
     int eos;
     unsigned page_count; ///< number of page buffered
     OGGPage page; ///< current page
@@ -85,6 +83,42 @@ typedef struct OGGContext {
     int ended;  ///< a new link could not be started, the packets that follow 
are dropped
 } OGGContext;
 
+/**
+ * Codec mapping of the muxer: the parts of the Ogg encapsulation that depend
+ * on the codec.
+ */
+struct OGGMuxerMapping {
+    enum AVCodecID codec_id;
+    size_t priv_data_size;  ///< size of OGGStreamContext.priv_data
+    int optional_extradata; ///< the headers can be built without extradata
+    int new_links;          ///< a new link can replace the current one
+    /**
+     * Build the header packets in OGGStreamContext.header, adjusting the
+     * stream time base when the codec sets its own.
+     */
+    int (*init)(AVFormatContext *s, AVStream *st);
+    /**
+     * @return why a new link cannot start with this packet, NULL if it can.
+     *         When NULL, every packet can start one.
+     */
+    const char *(*new_link_refused)(const AVStream *st, const AVPacket *pkt,
+                                    const uint8_t *new_extradata, size_t size);
+    /**
+     * @return the granule of a packet. When NULL, the granule is the
+     *         packet's end timestamp.
+     */
+    int64_t (*packet_granule)(AVStream *st, const AVPacket *pkt);
+    /**
+     * @return the timestamp of a granule. When NULL, the granule is the
+     *         timestamp.
+     */
+    int64_t (*granule_to_timestamp)(const AVStream *st, int64_t granule);
+    /**
+     * @return whether a granule marks a keyframe. When NULL, no granule does.
+     */
+    int (*key_granule)(const AVStream *st, int64_t granule);
+};
+
 #define OFFSET(x) offsetof(OGGContext, x)
 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
 
@@ -111,6 +145,7 @@ static void ogg_cleanup_stream(AVStream *st)
 
     for (int i = 0; i < 3; i++)
         av_freep(&oggstream->header[i]);
+    av_freep(&oggstream->priv_data);
 }
 
 static void ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
@@ -141,21 +176,21 @@ static void ogg_write_page(AVFormatContext *s, OGGPage 
*page, int extra_flags)
     oggstream->page_count--;
 }
 
-static int ogg_key_granule(OGGStreamContext *oggstream, int64_t granule)
+static int ogg_key_granule(const AVStream *st, int64_t granule)
 {
-    return (oggstream->kfgshift && !(granule & ((1<<oggstream->kfgshift)-1))) 
||
-           (oggstream->isvp8    && !((granule >> 3) & 0x07ffffff));
+    const OGGStreamContext *oggstream = st->priv_data;
+
+    return oggstream->mapping->key_granule &&
+           oggstream->mapping->key_granule(st, granule);
 }
 
-static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t 
granule)
+static int64_t ogg_granule_to_timestamp(const AVStream *st, int64_t granule)
 {
-    if (oggstream->kfgshift)
-        return (granule>>oggstream->kfgshift) +
-            (granule & ((1<<oggstream->kfgshift)-1));
-    else if (oggstream->isvp8)
-        return granule >> 32;
-    else
-        return granule;
+    const OGGStreamContext *oggstream = st->priv_data;
+
+    if (oggstream->mapping->granule_to_timestamp)
+        return oggstream->mapping->granule_to_timestamp(st, granule);
+    return granule;
 }
 
 static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage 
*page)
@@ -167,9 +202,9 @@ static int ogg_compare_granule(AVFormatContext *s, OGGPage 
*next, OGGPage *page)
     if (next->granule == -1 || page->granule == -1)
         return 0;
 
-    next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, 
next->granule),
+    next_granule = av_rescale_q(ogg_granule_to_timestamp(st2, next->granule),
                                 st2->time_base, AV_TIME_BASE_Q);
-    cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, 
page->granule),
+    cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st, page->granule),
                                 st ->time_base, AV_TIME_BASE_Q);
     return next_granule > cur_granule;
 }
@@ -195,7 +230,8 @@ static int ogg_buffer_page(AVFormatContext *s, 
OGGStreamContext *oggstream)
     }
     l->page = oggstream->page;
 
-    oggstream->page.start_granule = ogg_granule_to_timestamp(oggstream, 
oggstream->page.granule);
+    oggstream->page.start_granule = 
ogg_granule_to_timestamp(s->streams[oggstream->page.stream_index],
+                                                             
oggstream->page.granule);
     oggstream->page_count++;
     ogg_reset_cur_page(oggstream);
 
@@ -226,9 +262,9 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
     // least with old libogg versions.
     // Do not try to flush header packets though, that will create broken 
files.
     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !header &&
-        (ogg_granule_to_timestamp(oggstream, granule) >
-         ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1 ||
-         ogg_key_granule(oggstream, granule))) {
+        (ogg_granule_to_timestamp(st, granule) >
+         ogg_granule_to_timestamp(st, oggstream->last_granule) + 1 ||
+         ogg_key_granule(st, granule))) {
         if (oggstream->page.granule != -1 &&
             (ret = ogg_buffer_page(s, oggstream)) < 0)
             return ret;
@@ -270,7 +306,7 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
 
             int64_t start = av_rescale_q(page->start_granule, time_base,
                                          AV_TIME_BASE_Q);
-            int64_t next  = av_rescale_q(ogg_granule_to_timestamp(oggstream, 
page->granule),
+            int64_t next  = av_rescale_q(ogg_granule_to_timestamp(st, 
page->granule),
                                          time_base, AV_TIME_BASE_Q);
 
             if (page->segments_count == 255) {
@@ -328,6 +364,22 @@ static int ogg_build_flac_headers(AVCodecParameters *par,
     return 0;
 }
 
+static int flac_init(AVFormatContext *s, AVStream *st)
+{
+    int err = ogg_build_flac_headers(st->codecpar, st->priv_data,
+                                     s->flags & AVFMT_FLAG_BITEXACT,
+                                     &st->metadata);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
+    return err;
+}
+
+static const OGGMuxerMapping flac_mapping = {
+    .codec_id  = AV_CODEC_ID_FLAC,
+    .new_links = 1,
+    .init      = flac_init,
+};
+
 #define SPEEX_HEADER_SIZE 80
 
 static int ogg_build_speex_headers(AVCodecParameters *par,
@@ -357,6 +409,21 @@ static int ogg_build_speex_headers(AVCodecParameters *par,
     return 0;
 }
 
+static int speex_init(AVFormatContext *s, AVStream *st)
+{
+    int err = ogg_build_speex_headers(st->codecpar, st->priv_data,
+                                      s->flags & AVFMT_FLAG_BITEXACT,
+                                      &st->metadata);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
+    return err;
+}
+
+static const OGGMuxerMapping speex_mapping = {
+    .codec_id = AV_CODEC_ID_SPEEX,
+    .init     = speex_init,
+};
+
 #define OPUS_HEADER_SIZE 19
 
 static int ogg_build_opus_headers(AVCodecParameters *par,
@@ -387,6 +454,34 @@ static int ogg_build_opus_headers(AVCodecParameters *par,
     return 0;
 }
 
+static int opus_init(AVFormatContext *s, AVStream *st)
+{
+    int err;
+
+    avpriv_set_pts_info(st, 64, 1, OPUS_TIMESTAMP_RATE);
+    err = ogg_build_opus_headers(st->codecpar, st->priv_data,
+                                 s->flags & AVFMT_FLAG_BITEXACT,
+                                 &st->metadata, s->chapters, s->nb_chapters);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
+    return err;
+}
+
+static int64_t opus_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+
+    /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
+    return pkt->pts + pkt->duration + AV_RL16(oggstream->header[0] + 10);
+}
+
+static const OGGMuxerMapping opus_mapping = {
+    .codec_id       = AV_CODEC_ID_OPUS,
+    .new_links      = 1,
+    .init           = opus_init,
+    .packet_granule = opus_packet_granule,
+};
+
 #define VP8_HEADER_SIZE 26
 
 static int ogg_build_vp8_headers(AVFormatContext *s, AVStream *st,
@@ -433,11 +528,228 @@ static int ogg_build_vp8_headers(AVFormatContext *s, 
AVStream *st,
         bytestream_put_byte(&p, 0x20);
     }
 
-    oggstream->isvp8 = 1;
+    return 0;
+}
+
+static int vp8_init(AVFormatContext *s, AVStream *st)
+{
+    int err = ogg_build_vp8_headers(s, st, st->priv_data,
+                                    s->flags & AVFMT_FLAG_BITEXACT);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
+    return err;
+}
+
+static int64_t vp8_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    int64_t pts, invcnt, dist;
+    int visible;
+
+    visible = (pkt->data[0] >> 4) & 1;
+    pts     = pkt->pts + pkt->duration;
+    invcnt  = (oggstream->last_granule >> 30) & 3;
+    invcnt  = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
+    dist    = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule 
>> 3) & 0x07ffffff) + 1;
+
+    return (pts << 32) | (invcnt << 30) | (dist << 3);
+}
+
+static int64_t vp8_granule_to_timestamp(const AVStream *st, int64_t granule)
+{
+    return granule >> 32;
+}
+
+static int vp8_key_granule(const AVStream *st, int64_t granule)
+{
+    return !((granule >> 3) & 0x07ffffff);
+}
+
+static const OGGMuxerMapping vp8_mapping = {
+    .codec_id             = AV_CODEC_ID_VP8,
+    .optional_extradata   = 1,
+    .init                 = vp8_init,
+    .packet_granule       = vp8_packet_granule,
+    .granule_to_timestamp = vp8_granule_to_timestamp,
+    .key_granule          = vp8_key_granule,
+};
+
+/**
+ * Build the headers of a codec using the Xiph header layout: identification,
+ * comment and setup packets laced in the extradata.
+ *
+ * @param first_header_size the size of the identification header
+ * @param comment_type      the packet type of the comment header
+ * @param name              the codec name in the comment header
+ * @param framing_bit       whether the comment header ends with a framing bit
+ */
+static int ogg_build_xiph_headers(AVFormatContext *s, AVStream *st,
+                                  int first_header_size, int comment_type,
+                                  const char *name, int framing_bit)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    const uint8_t *header[3];
+    uint8_t *p;
+
+    if (avpriv_split_xiph_headers(st->codecpar->extradata, 
st->codecpar->extradata_size,
+                                  first_header_size, header, 
oggstream->header_len) < 0) {
+        av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    oggstream->header[0] = av_memdup(header[0], oggstream->header_len[0]);
+    oggstream->header[2] = av_memdup(header[2], oggstream->header_len[2]);
+    if (!oggstream->header[0] || !oggstream->header[2])
+        return AVERROR(ENOMEM);
+
+    p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
+                                &oggstream->header_len[1], &st->metadata,
+                                framing_bit, NULL, 0);
+    oggstream->header[1] = p;
+    if (!p)
+        return AVERROR(ENOMEM);
+
+    bytestream_put_byte(&p, comment_type);
+    bytestream_put_buffer(&p, name, 6);
 
     return 0;
 }
 
+static int vorbis_init(AVFormatContext *s, AVStream *st)
+{
+    return ogg_build_xiph_headers(s, st, 30, 3, "vorbis", 1);
+}
+
+static const OGGMuxerMapping vorbis_mapping = {
+    .codec_id  = AV_CODEC_ID_VORBIS,
+    .new_links = 1,
+    .init      = vorbis_init,
+};
+
+typedef struct TheoraMuxerContext {
+    int kfgshift; ///< width of the frame count since the last keyframe in the 
granule
+    int vrev;     ///< bitstream revision
+    int64_t last_kf_pts;
+} TheoraMuxerContext;
+
+static int theora_init(AVFormatContext *s, AVStream *st)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    TheoraMuxerContext *theora = oggstream->priv_data;
+    int den, num;
+    int err = ogg_build_xiph_headers(s, st, 42, 0x81, "theora", 0);
+
+    if (err < 0)
+        return err;
+
+    den = AV_RB32(oggstream->header[0] + 22);
+    num = AV_RB32(oggstream->header[0] + 26);
+    /* Make sure to use time base stored in the Theora stream header to write
+       correct timestamps */
+    if (st->time_base.num != num || st->time_base.den != den) {
+        av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
+               st->time_base.num, st->time_base.den, num, den);
+        avpriv_set_pts_info(st, 64, num, den);
+    }
+    /** KFGSHIFT is the width of the less significant section of the granule 
position
+        The less significant section is the frame count since the last 
keyframe */
+    theora->kfgshift = 
((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
+    theora->vrev = oggstream->header[0][9];
+    av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
+           theora->kfgshift, theora->vrev);
+
+    return 0;
+}
+
+/**
+ * Whether Theora headers set a frame rate other than the stream time base,
+ * which packets keep across links.
+ */
+static int ogg_theora_rate_changed(const AVStream *st, const uint8_t 
*extradata, size_t size)
+{
+    const uint8_t *header[3];
+    int header_len[3];
+
+    if (size > INT_MAX ||
+        avpriv_split_xiph_headers(extradata, size, 42, header, header_len) < 0)
+        return 0;
+    return av_cmp_q(st->time_base,
+                    (AVRational){ AV_RB32(header[0] + 26), AV_RB32(header[0] + 
22) }) != 0;
+}
+
+static const char *theora_new_link_refused(const AVStream *st, const AVPacket 
*pkt,
+                                           const uint8_t *new_extradata, 
size_t size)
+{
+    if (!new_extradata && !(pkt->flags & AV_PKT_FLAG_KEY))
+        return "New Theora links must start on a keyframe";
+    if (new_extradata && ogg_theora_rate_changed(st, new_extradata, size))
+        return "New Theora links cannot change the frame rate";
+    return NULL;
+}
+
+static int64_t theora_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    TheoraMuxerContext *theora = oggstream->priv_data;
+    int64_t pts = theora->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
+    int pframe_count;
+
+    if (pkt->flags & AV_PKT_FLAG_KEY)
+        theora->last_kf_pts = pts;
+    pframe_count = pts - theora->last_kf_pts;
+    // prevent frame count from overflow if key frame flag is not set
+    if (pframe_count >= (1<<theora->kfgshift)) {
+        theora->last_kf_pts += pframe_count;
+        pframe_count = 0;
+    }
+    return (theora->last_kf_pts<<theora->kfgshift) | pframe_count;
+}
+
+static int64_t theora_granule_to_timestamp(const AVStream *st, int64_t granule)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    const TheoraMuxerContext *theora = oggstream->priv_data;
+
+    return (granule>>theora->kfgshift) +
+        (granule & ((1<<theora->kfgshift)-1));
+}
+
+static int theora_key_granule(const AVStream *st, int64_t granule)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    const TheoraMuxerContext *theora = oggstream->priv_data;
+
+    return theora->kfgshift && !(granule & ((1<<theora->kfgshift)-1));
+}
+
+static const OGGMuxerMapping theora_mapping = {
+    .codec_id             = AV_CODEC_ID_THEORA,
+    .priv_data_size       = sizeof(TheoraMuxerContext),
+    .new_links            = 1,
+    .init                 = theora_init,
+    .new_link_refused     = theora_new_link_refused,
+    .packet_granule       = theora_packet_granule,
+    .granule_to_timestamp = theora_granule_to_timestamp,
+    .key_granule          = theora_key_granule,
+};
+
+static const OGGMuxerMapping *const ogg_mappings[] = {
+    &flac_mapping,
+    &opus_mapping,
+    &speex_mapping,
+    &theora_mapping,
+    &vorbis_mapping,
+    &vp8_mapping,
+};
+
+static const OGGMuxerMapping *ogg_find_mapping(enum AVCodecID codec_id)
+{
+    for (int i = 0; i < FF_ARRAY_ELEMS(ogg_mappings); i++)
+        if (ogg_mappings[i]->codec_id == codec_id)
+            return ogg_mappings[i];
+    return NULL;
+}
+
 static void ogg_write_pages(AVFormatContext *s, int flush)
 {
     OGGContext *ogg = s->priv_data;
@@ -498,25 +810,19 @@ static int ogg_init(AVFormatContext *s)
         AVStream *st = s->streams[i];
         unsigned serial_num;
 
-        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
-            if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
-                avpriv_set_pts_info(st, 64, 1, OPUS_TIMESTAMP_RATE);
-            else
-                avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
-        }
+        const OGGMuxerMapping *mapping = 
ogg_find_mapping(st->codecpar->codec_id);
+        int err;
 
-        if (st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&
-            st->codecpar->codec_id != AV_CODEC_ID_THEORA &&
-            st->codecpar->codec_id != AV_CODEC_ID_SPEEX  &&
-            st->codecpar->codec_id != AV_CODEC_ID_FLAC   &&
-            st->codecpar->codec_id != AV_CODEC_ID_OPUS   &&
-            st->codecpar->codec_id != AV_CODEC_ID_VP8) {
+        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
+            avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
+
+        if (!mapping) {
             av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
             return AVERROR(EINVAL);
         }
 
         if ((!st->codecpar->extradata || !st->codecpar->extradata_size) &&
-            st->codecpar->codec_id != AV_CODEC_ID_VP8) {
+            !mapping->optional_extradata) {
             av_log(s, AV_LOG_ERROR, "No extradata present\n");
             return AVERROR_INVALIDDATA;
         }
@@ -533,86 +839,18 @@ static int ogg_init(AVFormatContext *s)
         }
 
         oggstream->page.stream_index = i;
+        oggstream->mapping = mapping;
+        if (mapping->priv_data_size) {
+            oggstream->priv_data = av_mallocz(mapping->priv_data_size);
+            if (!oggstream->priv_data)
+                return AVERROR(ENOMEM);
+        }
 
         av_dict_copy(&st->metadata, s->metadata, AV_DICT_DONT_OVERWRITE);
 
-        if (st->codecpar->codec_id == AV_CODEC_ID_FLAC) {
-            int err = ogg_build_flac_headers(st->codecpar, oggstream,
-                                             s->flags & AVFMT_FLAG_BITEXACT,
-                                             &st->metadata);
-            if (err) {
-                av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
-                return err;
-            }
-        } else if (st->codecpar->codec_id == AV_CODEC_ID_SPEEX) {
-            int err = ogg_build_speex_headers(st->codecpar, oggstream,
-                                              s->flags & AVFMT_FLAG_BITEXACT,
-                                              &st->metadata);
-            if (err) {
-                av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
-                return err;
-            }
-        } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS) {
-            int err = ogg_build_opus_headers(st->codecpar, oggstream,
-                                             s->flags & AVFMT_FLAG_BITEXACT,
-                                             &st->metadata, s->chapters, 
s->nb_chapters);
-            if (err) {
-                av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
-                return err;
-            }
-        } else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
-            int err = ogg_build_vp8_headers(s, st, oggstream,
-                                            s->flags & AVFMT_FLAG_BITEXACT);
-            if (err) {
-                av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
-                return err;
-            }
-        } else {
-            const uint8_t *header[3];
-            uint8_t *p;
-            const char *cstr = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 
"vorbis" : "theora";
-            int header_type = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 3 
: 0x81;
-            int framing_bit = st->codecpar->codec_id == AV_CODEC_ID_VORBIS ? 1 
: 0;
-
-            if (avpriv_split_xiph_headers(st->codecpar->extradata, 
st->codecpar->extradata_size,
-                                      st->codecpar->codec_id == 
AV_CODEC_ID_VORBIS ? 30 : 42,
-                                      header, oggstream->header_len) < 0) {
-                av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
-                return AVERROR_INVALIDDATA;
-            }
-
-            oggstream->header[0] = av_memdup(header[0], 
oggstream->header_len[0]);
-            oggstream->header[2] = av_memdup(header[2], 
oggstream->header_len[2]);
-            if (!oggstream->header[0] || !oggstream->header[2])
-                return AVERROR(ENOMEM);
-
-            p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
-                                        &oggstream->header_len[1], 
&st->metadata,
-                                        framing_bit, NULL, 0);
-            oggstream->header[1] = p;
-            if (!p)
-                return AVERROR(ENOMEM);
-
-            bytestream_put_byte(&p, header_type);
-            bytestream_put_buffer(&p, cstr, 6);
-
-            if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
-                int den = AV_RB32(oggstream->header[0] + 22), num = 
AV_RB32(oggstream->header[0] + 26);
-                /* Make sure to use time base stored in the Theora stream 
header to write
-                   correct timestamps */
-                if (st->time_base.num != num || st->time_base.den != den) {
-                    av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to 
%d/%d\n",
-                           st->time_base.num, st->time_base.den, num, den);
-                    avpriv_set_pts_info(st, 64, num, den);
-                }
-                /** KFGSHIFT is the width of the less significant section of 
the granule position
-                    The less significant section is the frame count since the 
last keyframe */
-                oggstream->kfgshift = 
((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
-                oggstream->vrev = oggstream->header[0][9];
-                av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
-                       oggstream->kfgshift, oggstream->vrev);
-            }
-        }
+        err = mapping->init(s, st);
+        if (err < 0)
+            return err;
 
         if (s->flags & AVFMT_FLAG_BITEXACT && ogg->serial_offset >= 0)
             serial_num = i + ogg->serial_offset;
@@ -668,22 +906,6 @@ static int ogg_write_header(AVFormatContext *s)
     return 0;
 }
 
-/**
- * Whether Theora headers set a frame rate other than the stream time base,
- * which packets keep across links.
- */
-static int ogg_theora_rate_changed(const AVStream *st, const uint8_t 
*extradata, size_t size)
-{
-    const uint8_t *header[3];
-    int header_len[3];
-
-    if (size > INT_MAX ||
-        avpriv_split_xiph_headers(extradata, size, 42, header, header_len) < 0)
-        return 0;
-    return av_cmp_q(st->time_base,
-                    (AVRational){ AV_RB32(header[0] + 26), AV_RB32(header[0] + 
22) }) != 0;
-}
-
 /**
  * Keep the current link when a new one cannot be started. New metadata is
  * then dropped, while new extradata ends the output, as the packets that
@@ -707,6 +929,7 @@ static int ogg_skip_new_link(AVFormatContext *s, const 
uint8_t *new_extradata,
 static int ogg_check_new_link(AVFormatContext *s, AVPacket *pkt)
 {
     int ret = 0;
+    const char *refused;
     size_t metadata_size, extradata_size;
     OGGContext *oggcontext = s->priv_data;
     AVStream *st = s->streams[pkt->stream_index];
@@ -733,20 +956,13 @@ static int ogg_check_new_link(AVFormatContext *s, 
AVPacket *pkt)
     if (s->nb_streams > 1)
         return ogg_skip_new_link(s, new_extradata, "Multiple streams present");
 
-    if (par->codec_id != AV_CODEC_ID_VORBIS &&
-        par->codec_id != AV_CODEC_ID_FLAC &&
-        par->codec_id != AV_CODEC_ID_OPUS &&
-        par->codec_id != AV_CODEC_ID_THEORA)
+    if (!oggstream->mapping->new_links)
         return ogg_skip_new_link(s, new_extradata,
                                  "New links are only supported for vorbis, 
flac, opus and theora streams");
 
-    if (par->codec_id == AV_CODEC_ID_THEORA && !new_extradata &&
-        !(pkt->flags & AV_PKT_FLAG_KEY))
-        return ogg_skip_new_link(s, NULL, "New Theora links must start on a 
keyframe");
-
-    if (par->codec_id == AV_CODEC_ID_THEORA && new_extradata &&
-        ogg_theora_rate_changed(st, new_extradata, extradata_size))
-        return ogg_skip_new_link(s, new_extradata, "New Theora links cannot 
change the frame rate");
+    if (oggstream->mapping->new_link_refused &&
+        (refused = oggstream->mapping->new_link_refused(st, pkt, 
new_extradata, extradata_size)))
+        return ogg_skip_new_link(s, new_extradata, refused);
 
     ret = ogg_write_trailer(s);
     if (ret < 0)
@@ -798,33 +1014,9 @@ static int ogg_write_packet_internal(AVFormatContext *s, 
AVPacket *pkt)
     if (ret < 0 || oggcontext->ended)
         return ret;
 
-    if (st->codecpar->codec_id == AV_CODEC_ID_THEORA) {
-        int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + 
pkt->duration;
-        int pframe_count;
-        if (pkt->flags & AV_PKT_FLAG_KEY)
-            oggstream->last_kf_pts = pts;
-        pframe_count = pts - oggstream->last_kf_pts;
-        // prevent frame count from overflow if key frame flag is not set
-        if (pframe_count >= (1<<oggstream->kfgshift)) {
-            oggstream->last_kf_pts += pframe_count;
-            pframe_count = 0;
-        }
-        granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
-    } else if (st->codecpar->codec_id == AV_CODEC_ID_OPUS)
-        /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
-        granule = pkt->pts + pkt->duration + AV_RL16(oggstream->header[0] + 
10);
-    else if (st->codecpar->codec_id == AV_CODEC_ID_VP8) {
-        int64_t pts, invcnt, dist;
-        int visible;
-
-        visible = (pkt->data[0] >> 4) & 1;
-        pts     = pkt->pts + pkt->duration;
-        invcnt  = (oggstream->last_granule >> 30) & 3;
-        invcnt  = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
-        dist    = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : 
((oggstream->last_granule >> 3) & 0x07ffffff) + 1;
-
-        granule = (pts << 32) | (invcnt << 30) | (dist << 3);
-    } else
+    if (oggstream->mapping->packet_granule)
+        granule = oggstream->mapping->packet_granule(st, pkt);
+    else
         granule = pkt->pts + pkt->duration;
 
     if (oggstream->page.start_granule == AV_NOPTS_VALUE)
-- 
2.54.1


>From d5db06d99e4c5599ab30c3fc30f31976e04b0f84 Mon Sep 17 00:00:00 2001
From: Romain Beauxis <[email protected]>
Date: Sun, 22 Nov 2026 15:12:56 -0500
Subject: [PATCH 6/6] avformat/ogg/muxer: move the codec mappings to ogg/muxer/

Each codec mapping gets its own file, next to the generic muxer code.
The stream context, the mapping description and the helpers shared by
the mappings move to the muxer header.

The header builders already in the muxer take the <codec>_ prefix of
the other functions of their file, as in the demuxer mappings.
---
 MAINTAINERS                    |   3 +-
 libavformat/ogg/Makefile       |  10 +-
 libavformat/ogg/muxer.c        | 488 +--------------------------------
 libavformat/ogg/muxer.h        | 116 ++++++++
 libavformat/ogg/muxer/flac.c   |  77 ++++++
 libavformat/ogg/muxer/opus.c   |  85 ++++++
 libavformat/ogg/muxer/speex.c  |  69 +++++
 libavformat/ogg/muxer/theora.c | 134 +++++++++
 libavformat/ogg/muxer/vorbis.c |  33 +++
 libavformat/ogg/muxer/vp8.c    | 119 ++++++++
 10 files changed, 650 insertions(+), 484 deletions(-)
 create mode 100644 libavformat/ogg/muxer/flac.c
 create mode 100644 libavformat/ogg/muxer/opus.c
 create mode 100644 libavformat/ogg/muxer/speex.c
 create mode 100644 libavformat/ogg/muxer/theora.c
 create mode 100644 libavformat/ogg/muxer/vorbis.c
 create mode 100644 libavformat/ogg/muxer/vp8.c

diff --git a/MAINTAINERS b/MAINTAINERS
index 60c0fc62457..89abb34d8e8 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -471,7 +471,8 @@ Muxers/Demuxers:
   nut*                                  Michael Niedermayer
   nuv.c                                 Reimar Doeffinger
   ogg/demuxer.c, ogg/demuxer.h          David Conrad, Romain Beauxis
-  ogg/muxer.c                           Baptiste Coudurier, Romain Beauxis
+  ogg/muxer.c, ogg/muxer.h              Baptiste Coudurier, Romain Beauxis
+  ogg/muxer/*                           Baptiste Coudurier, Romain Beauxis
   ogg/demuxer/*                         David Conrad, Romain Beauxis
   oma.c                                 Maxim Poliakovski
   pp_bnk.c                              Zane van Iperen
diff --git a/libavformat/ogg/Makefile b/libavformat/ogg/Makefile
index b1e41c54a1d..5a0c50d0901 100644
--- a/libavformat/ogg/Makefile
+++ b/libavformat/ogg/Makefile
@@ -3,6 +3,7 @@ HEADER_DIRS += ogg
 clean::
        $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/%)
        $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/demuxer/%)
+       $(RM) $(CLEANSUFFIXES:%=libavformat/ogg/muxer/%)
 
 OBJS-$(CONFIG_OGG_DEMUXER) +=  \
     ogg/demuxer.o              \
@@ -17,7 +18,14 @@ OBJS-$(CONFIG_OGG_DEMUXER) +=  \
     ogg/demuxer/vp8.o          \
 
 OBJS-$(CONFIG_OGA_MUXER)   += ogg/muxer.o
-OBJS-$(CONFIG_OGG_MUXER)   += ogg/muxer.o
+OBJS-$(CONFIG_OGG_MUXER)   += ogg/muxer.o              \
+                              ogg/muxer/flac.o         \
+                              ogg/muxer/opus.o         \
+                              ogg/muxer/speex.o        \
+                              ogg/muxer/theora.o       \
+                              ogg/muxer/vorbis.o       \
+                              ogg/muxer/vp8.o          \
+
 OBJS-$(CONFIG_OGV_MUXER)   += ogg/muxer.o
 OBJS-$(CONFIG_OPUS_MUXER)  += ogg/muxer.o
 OBJS-$(CONFIG_SPEEX_MUXER) += ogg/muxer.o
diff --git a/libavformat/ogg/muxer.c b/libavformat/ogg/muxer.c
index ffd16b5a63f..c23fee8b9e8 100644
--- a/libavformat/ogg/muxer.c
+++ b/libavformat/ogg/muxer.c
@@ -28,47 +28,12 @@
 #include "libavutil/mem.h"
 #include "libavutil/opt.h"
 #include "libavutil/random_seed.h"
-#include "libavcodec/xiph.h"
 #include "libavcodec/bytestream.h"
-#include "libavcodec/flac.h"
-#include "libavcodec/opus/tab.h"
 #include "libavformat/avformat.h"
-#include "libavformat/avio_internal.h"
 #include "libavformat/internal.h"
 #include "libavformat/mux.h"
-#include "libavformat/version.h"
-#include "libavformat/vorbis/comment.h"
 #include "muxer.h"
 
-#define MAX_PAGE_SIZE 65025
-
-typedef struct OGGPage {
-    int64_t start_granule;
-    int64_t granule;
-    int stream_index;
-    uint8_t flags;
-    uint8_t segments_count;
-    uint8_t segments[255];
-    uint8_t data[MAX_PAGE_SIZE];
-    uint16_t size;
-} OGGPage;
-
-typedef struct OGGMuxerMapping OGGMuxerMapping;
-
-typedef struct OGGStreamContext {
-    unsigned page_counter;
-    uint8_t *header[3];
-    int header_len[3];
-    const OGGMuxerMapping *mapping;
-    void *priv_data; ///< state of the mapping
-    int eos;
-    unsigned page_count; ///< number of page buffered
-    OGGPage page; ///< current page
-    unsigned serial_num; ///< serial number
-    int64_t last_granule; ///< last packet granule
-    int packet_seen; ///< true when packets have been submitted
-} OGGStreamContext;
-
 typedef struct OGGPageList {
     OGGPage page;
     struct OGGPageList *next;
@@ -83,42 +48,6 @@ typedef struct OGGContext {
     int ended;  ///< a new link could not be started, the packets that follow 
are dropped
 } OGGContext;
 
-/**
- * Codec mapping of the muxer: the parts of the Ogg encapsulation that depend
- * on the codec.
- */
-struct OGGMuxerMapping {
-    enum AVCodecID codec_id;
-    size_t priv_data_size;  ///< size of OGGStreamContext.priv_data
-    int optional_extradata; ///< the headers can be built without extradata
-    int new_links;          ///< a new link can replace the current one
-    /**
-     * Build the header packets in OGGStreamContext.header, adjusting the
-     * stream time base when the codec sets its own.
-     */
-    int (*init)(AVFormatContext *s, AVStream *st);
-    /**
-     * @return why a new link cannot start with this packet, NULL if it can.
-     *         When NULL, every packet can start one.
-     */
-    const char *(*new_link_refused)(const AVStream *st, const AVPacket *pkt,
-                                    const uint8_t *new_extradata, size_t size);
-    /**
-     * @return the granule of a packet. When NULL, the granule is the
-     *         packet's end timestamp.
-     */
-    int64_t (*packet_granule)(AVStream *st, const AVPacket *pkt);
-    /**
-     * @return the timestamp of a granule. When NULL, the granule is the
-     *         timestamp.
-     */
-    int64_t (*granule_to_timestamp)(const AVStream *st, int64_t granule);
-    /**
-     * @return whether a granule marks a keyframe. When NULL, no granule does.
-     */
-    int (*key_granule)(const AVStream *st, int64_t granule);
-};
-
 #define OFFSET(x) offsetof(OGGContext, x)
 #define PARAM AV_OPT_FLAG_ENCODING_PARAM
 
@@ -328,418 +257,13 @@ static int ogg_buffer_data(AVFormatContext *s, AVStream 
*st,
     return 0;
 }
 
-static int ogg_build_flac_headers(AVCodecParameters *par,
-                                  OGGStreamContext *oggstream, int bitexact,
-                                  AVDictionary **m)
-{
-    uint8_t *p;
-
-    if (par->extradata_size < FLAC_STREAMINFO_SIZE)
-        return AVERROR(EINVAL);
-
-    // first packet: STREAMINFO
-    oggstream->header_len[0] = 51;
-    oggstream->header[0] = av_mallocz(51); // per ogg flac specs
-    p = oggstream->header[0];
-    if (!p)
-        return AVERROR(ENOMEM);
-    bytestream_put_byte(&p, 0x7F);
-    bytestream_put_buffer(&p, "FLAC", 4);
-    bytestream_put_byte(&p, 1); // major version
-    bytestream_put_byte(&p, 0); // minor version
-    bytestream_put_be16(&p, 1); // headers packets without this one
-    bytestream_put_buffer(&p, "fLaC", 4);
-    bytestream_put_byte(&p, 0x00); // streaminfo
-    bytestream_put_be24(&p, 34);
-    bytestream_put_buffer(&p, par->extradata, FLAC_STREAMINFO_SIZE);
-
-    // second packet: VorbisComment
-    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0, 
NULL, 0);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[1] = p;
-    bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
-    bytestream_put_be24(&p, oggstream->header_len[1] - 4);
-
-    return 0;
-}
-
-static int flac_init(AVFormatContext *s, AVStream *st)
-{
-    int err = ogg_build_flac_headers(st->codecpar, st->priv_data,
-                                     s->flags & AVFMT_FLAG_BITEXACT,
-                                     &st->metadata);
-    if (err)
-        av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
-    return err;
-}
-
-static const OGGMuxerMapping flac_mapping = {
-    .codec_id  = AV_CODEC_ID_FLAC,
-    .new_links = 1,
-    .init      = flac_init,
-};
-
-#define SPEEX_HEADER_SIZE 80
-
-static int ogg_build_speex_headers(AVCodecParameters *par,
-                                   OGGStreamContext *oggstream, int bitexact,
-                                   AVDictionary **m)
-{
-    uint8_t *p;
-
-    if (par->extradata_size < SPEEX_HEADER_SIZE)
-        return AVERROR_INVALIDDATA;
-
-    // first packet: Speex header
-    p = av_mallocz(SPEEX_HEADER_SIZE);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[0] = p;
-    oggstream->header_len[0] = SPEEX_HEADER_SIZE;
-    bytestream_put_buffer(&p, par->extradata, SPEEX_HEADER_SIZE);
-    AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
-
-    // second packet: VorbisComment
-    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0, 
NULL, 0);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[1] = p;
-
-    return 0;
-}
-
-static int speex_init(AVFormatContext *s, AVStream *st)
-{
-    int err = ogg_build_speex_headers(st->codecpar, st->priv_data,
-                                      s->flags & AVFMT_FLAG_BITEXACT,
-                                      &st->metadata);
-    if (err)
-        av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
-    return err;
-}
-
-static const OGGMuxerMapping speex_mapping = {
-    .codec_id = AV_CODEC_ID_SPEEX,
-    .init     = speex_init,
-};
-
-#define OPUS_HEADER_SIZE 19
-
-static int ogg_build_opus_headers(AVCodecParameters *par,
-                                  OGGStreamContext *oggstream, int bitexact,
-                                  AVDictionary **m, AVChapter **chapters,
-                                  unsigned int nb_chapters)
-{
-    uint8_t *p;
-
-    if (par->extradata_size < OPUS_HEADER_SIZE)
-        return AVERROR_INVALIDDATA;
-
-    /* first packet: Opus header */
-    p = av_mallocz(par->extradata_size);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[0] = p;
-    oggstream->header_len[0] = par->extradata_size;
-    bytestream_put_buffer(&p, par->extradata, par->extradata_size);
-
-    /* second packet: VorbisComment */
-    p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0, 
chapters, nb_chapters);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[1] = p;
-    bytestream_put_buffer(&p, "OpusTags", 8);
-
-    return 0;
-}
-
-static int opus_init(AVFormatContext *s, AVStream *st)
-{
-    int err;
-
-    avpriv_set_pts_info(st, 64, 1, OPUS_TIMESTAMP_RATE);
-    err = ogg_build_opus_headers(st->codecpar, st->priv_data,
-                                 s->flags & AVFMT_FLAG_BITEXACT,
-                                 &st->metadata, s->chapters, s->nb_chapters);
-    if (err)
-        av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
-    return err;
-}
-
-static int64_t opus_packet_granule(AVStream *st, const AVPacket *pkt)
-{
-    const OGGStreamContext *oggstream = st->priv_data;
-
-    /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
-    return pkt->pts + pkt->duration + AV_RL16(oggstream->header[0] + 10);
-}
-
-static const OGGMuxerMapping opus_mapping = {
-    .codec_id       = AV_CODEC_ID_OPUS,
-    .new_links      = 1,
-    .init           = opus_init,
-    .packet_granule = opus_packet_granule,
-};
-
-#define VP8_HEADER_SIZE 26
-
-static int ogg_build_vp8_headers(AVFormatContext *s, AVStream *st,
-                                 OGGStreamContext *oggstream, int bitexact)
-{
-    AVCodecParameters *par = st->codecpar;
-    uint8_t *p;
-
-    /* first packet: VP8 header */
-    p = av_mallocz(VP8_HEADER_SIZE);
-    if (!p)
-        return AVERROR(ENOMEM);
-    oggstream->header[0] = p;
-    oggstream->header_len[0] = VP8_HEADER_SIZE;
-    bytestream_put_byte(&p, 0x4f); // HDRID
-    bytestream_put_buffer(&p, "VP80", 4); // Identifier
-    bytestream_put_byte(&p, 1); // HDRTYP
-    bytestream_put_byte(&p, 1); // VMAJ
-    bytestream_put_byte(&p, 0); // VMIN
-    bytestream_put_be16(&p, par->width);
-    bytestream_put_be16(&p, par->height);
-    bytestream_put_be24(&p, par->sample_aspect_ratio.num);
-    bytestream_put_be24(&p, par->sample_aspect_ratio.den);
-    if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0) {
-        // OggVP8 requires pts to increase by 1 per visible frame, so use the 
least common
-        // multiple framerate if available.
-        av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
-               st->time_base.num, st->time_base.den,
-               st->r_frame_rate.den, st->r_frame_rate.num);
-        avpriv_set_pts_info(st, 64, st->r_frame_rate.den, 
st->r_frame_rate.num);
-    }
-    bytestream_put_be32(&p, st->time_base.den);
-    bytestream_put_be32(&p, st->time_base.num);
-
-    /* optional second packet: VorbisComment */
-    if (av_dict_count(st->metadata)) {
-        p = ogg_write_vorbiscomment(7, bitexact, &oggstream->header_len[1], 
&st->metadata, 0, NULL, 0);
-        if (!p)
-            return AVERROR(ENOMEM);
-        oggstream->header[1] = p;
-        bytestream_put_byte(&p, 0x4f); // HDRID
-        bytestream_put_buffer(&p, "VP80", 4); // Identifier
-        bytestream_put_byte(&p, 2); // HDRTYP
-        bytestream_put_byte(&p, 0x20);
-    }
-
-    return 0;
-}
-
-static int vp8_init(AVFormatContext *s, AVStream *st)
-{
-    int err = ogg_build_vp8_headers(s, st, st->priv_data,
-                                    s->flags & AVFMT_FLAG_BITEXACT);
-    if (err)
-        av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
-    return err;
-}
-
-static int64_t vp8_packet_granule(AVStream *st, const AVPacket *pkt)
-{
-    const OGGStreamContext *oggstream = st->priv_data;
-    int64_t pts, invcnt, dist;
-    int visible;
-
-    visible = (pkt->data[0] >> 4) & 1;
-    pts     = pkt->pts + pkt->duration;
-    invcnt  = (oggstream->last_granule >> 30) & 3;
-    invcnt  = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
-    dist    = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule 
>> 3) & 0x07ffffff) + 1;
-
-    return (pts << 32) | (invcnt << 30) | (dist << 3);
-}
-
-static int64_t vp8_granule_to_timestamp(const AVStream *st, int64_t granule)
-{
-    return granule >> 32;
-}
-
-static int vp8_key_granule(const AVStream *st, int64_t granule)
-{
-    return !((granule >> 3) & 0x07ffffff);
-}
-
-static const OGGMuxerMapping vp8_mapping = {
-    .codec_id             = AV_CODEC_ID_VP8,
-    .optional_extradata   = 1,
-    .init                 = vp8_init,
-    .packet_granule       = vp8_packet_granule,
-    .granule_to_timestamp = vp8_granule_to_timestamp,
-    .key_granule          = vp8_key_granule,
-};
-
-/**
- * Build the headers of a codec using the Xiph header layout: identification,
- * comment and setup packets laced in the extradata.
- *
- * @param first_header_size the size of the identification header
- * @param comment_type      the packet type of the comment header
- * @param name              the codec name in the comment header
- * @param framing_bit       whether the comment header ends with a framing bit
- */
-static int ogg_build_xiph_headers(AVFormatContext *s, AVStream *st,
-                                  int first_header_size, int comment_type,
-                                  const char *name, int framing_bit)
-{
-    OGGStreamContext *oggstream = st->priv_data;
-    const uint8_t *header[3];
-    uint8_t *p;
-
-    if (avpriv_split_xiph_headers(st->codecpar->extradata, 
st->codecpar->extradata_size,
-                                  first_header_size, header, 
oggstream->header_len) < 0) {
-        av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
-        return AVERROR_INVALIDDATA;
-    }
-
-    oggstream->header[0] = av_memdup(header[0], oggstream->header_len[0]);
-    oggstream->header[2] = av_memdup(header[2], oggstream->header_len[2]);
-    if (!oggstream->header[0] || !oggstream->header[2])
-        return AVERROR(ENOMEM);
-
-    p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
-                                &oggstream->header_len[1], &st->metadata,
-                                framing_bit, NULL, 0);
-    oggstream->header[1] = p;
-    if (!p)
-        return AVERROR(ENOMEM);
-
-    bytestream_put_byte(&p, comment_type);
-    bytestream_put_buffer(&p, name, 6);
-
-    return 0;
-}
-
-static int vorbis_init(AVFormatContext *s, AVStream *st)
-{
-    return ogg_build_xiph_headers(s, st, 30, 3, "vorbis", 1);
-}
-
-static const OGGMuxerMapping vorbis_mapping = {
-    .codec_id  = AV_CODEC_ID_VORBIS,
-    .new_links = 1,
-    .init      = vorbis_init,
-};
-
-typedef struct TheoraMuxerContext {
-    int kfgshift; ///< width of the frame count since the last keyframe in the 
granule
-    int vrev;     ///< bitstream revision
-    int64_t last_kf_pts;
-} TheoraMuxerContext;
-
-static int theora_init(AVFormatContext *s, AVStream *st)
-{
-    OGGStreamContext *oggstream = st->priv_data;
-    TheoraMuxerContext *theora = oggstream->priv_data;
-    int den, num;
-    int err = ogg_build_xiph_headers(s, st, 42, 0x81, "theora", 0);
-
-    if (err < 0)
-        return err;
-
-    den = AV_RB32(oggstream->header[0] + 22);
-    num = AV_RB32(oggstream->header[0] + 26);
-    /* Make sure to use time base stored in the Theora stream header to write
-       correct timestamps */
-    if (st->time_base.num != num || st->time_base.den != den) {
-        av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
-               st->time_base.num, st->time_base.den, num, den);
-        avpriv_set_pts_info(st, 64, num, den);
-    }
-    /** KFGSHIFT is the width of the less significant section of the granule 
position
-        The less significant section is the frame count since the last 
keyframe */
-    theora->kfgshift = 
((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
-    theora->vrev = oggstream->header[0][9];
-    av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
-           theora->kfgshift, theora->vrev);
-
-    return 0;
-}
-
-/**
- * Whether Theora headers set a frame rate other than the stream time base,
- * which packets keep across links.
- */
-static int ogg_theora_rate_changed(const AVStream *st, const uint8_t 
*extradata, size_t size)
-{
-    const uint8_t *header[3];
-    int header_len[3];
-
-    if (size > INT_MAX ||
-        avpriv_split_xiph_headers(extradata, size, 42, header, header_len) < 0)
-        return 0;
-    return av_cmp_q(st->time_base,
-                    (AVRational){ AV_RB32(header[0] + 26), AV_RB32(header[0] + 
22) }) != 0;
-}
-
-static const char *theora_new_link_refused(const AVStream *st, const AVPacket 
*pkt,
-                                           const uint8_t *new_extradata, 
size_t size)
-{
-    if (!new_extradata && !(pkt->flags & AV_PKT_FLAG_KEY))
-        return "New Theora links must start on a keyframe";
-    if (new_extradata && ogg_theora_rate_changed(st, new_extradata, size))
-        return "New Theora links cannot change the frame rate";
-    return NULL;
-}
-
-static int64_t theora_packet_granule(AVStream *st, const AVPacket *pkt)
-{
-    OGGStreamContext *oggstream = st->priv_data;
-    TheoraMuxerContext *theora = oggstream->priv_data;
-    int64_t pts = theora->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
-    int pframe_count;
-
-    if (pkt->flags & AV_PKT_FLAG_KEY)
-        theora->last_kf_pts = pts;
-    pframe_count = pts - theora->last_kf_pts;
-    // prevent frame count from overflow if key frame flag is not set
-    if (pframe_count >= (1<<theora->kfgshift)) {
-        theora->last_kf_pts += pframe_count;
-        pframe_count = 0;
-    }
-    return (theora->last_kf_pts<<theora->kfgshift) | pframe_count;
-}
-
-static int64_t theora_granule_to_timestamp(const AVStream *st, int64_t granule)
-{
-    const OGGStreamContext *oggstream = st->priv_data;
-    const TheoraMuxerContext *theora = oggstream->priv_data;
-
-    return (granule>>theora->kfgshift) +
-        (granule & ((1<<theora->kfgshift)-1));
-}
-
-static int theora_key_granule(const AVStream *st, int64_t granule)
-{
-    const OGGStreamContext *oggstream = st->priv_data;
-    const TheoraMuxerContext *theora = oggstream->priv_data;
-
-    return theora->kfgshift && !(granule & ((1<<theora->kfgshift)-1));
-}
-
-static const OGGMuxerMapping theora_mapping = {
-    .codec_id             = AV_CODEC_ID_THEORA,
-    .priv_data_size       = sizeof(TheoraMuxerContext),
-    .new_links            = 1,
-    .init                 = theora_init,
-    .new_link_refused     = theora_new_link_refused,
-    .packet_granule       = theora_packet_granule,
-    .granule_to_timestamp = theora_granule_to_timestamp,
-    .key_granule          = theora_key_granule,
-};
-
 static const OGGMuxerMapping *const ogg_mappings[] = {
-    &flac_mapping,
-    &opus_mapping,
-    &speex_mapping,
-    &theora_mapping,
-    &vorbis_mapping,
-    &vp8_mapping,
+    &ff_ogg_flac_muxer_mapping,
+    &ff_ogg_opus_muxer_mapping,
+    &ff_ogg_speex_muxer_mapping,
+    &ff_ogg_theora_muxer_mapping,
+    &ff_ogg_vorbis_muxer_mapping,
+    &ff_ogg_vp8_muxer_mapping,
 };
 
 static const OGGMuxerMapping *ogg_find_mapping(enum AVCodecID codec_id)
diff --git a/libavformat/ogg/muxer.h b/libavformat/ogg/muxer.h
index a759cb136dc..d1cfb9f77f6 100644
--- a/libavformat/ogg/muxer.h
+++ b/libavformat/ogg/muxer.h
@@ -24,7 +24,10 @@
 
 #include <stdint.h>
 
+#include "libavcodec/bytestream.h"
+#include "libavcodec/xiph.h"
 #include "libavutil/dict.h"
+#include "libavutil/log.h"
 #include "libavutil/mem.h"
 #include "libavformat/avformat.h"
 #include "libavformat/avio_internal.h"
@@ -32,6 +35,71 @@
 #include "libavformat/version.h"
 #include "libavformat/vorbis/comment.h"
 
+#define MAX_PAGE_SIZE 65025
+
+typedef struct OGGPage {
+    int64_t start_granule;
+    int64_t granule;
+    int stream_index;
+    uint8_t flags;
+    uint8_t segments_count;
+    uint8_t segments[255];
+    uint8_t data[MAX_PAGE_SIZE];
+    uint16_t size;
+} OGGPage;
+
+typedef struct OGGMuxerMapping OGGMuxerMapping;
+
+typedef struct OGGStreamContext {
+    unsigned page_counter;
+    uint8_t *header[3];
+    int header_len[3];
+    const OGGMuxerMapping *mapping;
+    void *priv_data; ///< state of the mapping
+    int eos;
+    unsigned page_count; ///< number of page buffered
+    OGGPage page; ///< current page
+    unsigned serial_num; ///< serial number
+    int64_t last_granule; ///< last packet granule
+    int packet_seen; ///< true when packets have been submitted
+} OGGStreamContext;
+
+/**
+ * Codec mapping of the muxer: the parts of the Ogg encapsulation that depend
+ * on the codec.
+ */
+struct OGGMuxerMapping {
+    enum AVCodecID codec_id;
+    size_t priv_data_size;  ///< size of OGGStreamContext.priv_data
+    int optional_extradata; ///< the headers can be built without extradata
+    int new_links;          ///< a new link can replace the current one
+    /**
+     * Build the header packets in OGGStreamContext.header, adjusting the
+     * stream time base when the codec sets its own.
+     */
+    int (*init)(AVFormatContext *s, AVStream *st);
+    /**
+     * @return why a new link cannot start with this packet, NULL if it can.
+     *         When NULL, every packet can start one.
+     */
+    const char *(*new_link_refused)(const AVStream *st, const AVPacket *pkt,
+                                    const uint8_t *new_extradata, size_t size);
+    /**
+     * @return the granule of a packet. When NULL, the granule is the
+     *         packet's end timestamp.
+     */
+    int64_t (*packet_granule)(AVStream *st, const AVPacket *pkt);
+    /**
+     * @return the timestamp of a granule. When NULL, the granule is the
+     *         timestamp.
+     */
+    int64_t (*granule_to_timestamp)(const AVStream *st, int64_t granule);
+    /**
+     * @return whether a granule marks a keyframe. When NULL, no granule does.
+     */
+    int (*key_granule)(const AVStream *st, int64_t granule);
+};
+
 /**
  * Allocate a comment header packet holding a VorbisComment. The metadata is
  * converted to VorbisComment field names in place.
@@ -72,4 +140,52 @@ static inline uint8_t *ogg_write_vorbiscomment(int64_t 
offset, int bitexact,
     return p;
 }
 
+/**
+ * Build the headers of a codec using the Xiph header layout: identification,
+ * comment and setup packets laced in the extradata.
+ *
+ * @param first_header_size the size of the identification header
+ * @param comment_type      the packet type of the comment header
+ * @param name              the codec name in the comment header
+ * @param framing_bit       whether the comment header ends with a framing bit
+ */
+static inline int ogg_build_xiph_headers(AVFormatContext *s, AVStream *st,
+                                         int first_header_size, int 
comment_type,
+                                         const char *name, int framing_bit)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    const uint8_t *header[3];
+    uint8_t *p;
+
+    if (avpriv_split_xiph_headers(st->codecpar->extradata, 
st->codecpar->extradata_size,
+                                  first_header_size, header, 
oggstream->header_len) < 0) {
+        av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    oggstream->header[0] = av_memdup(header[0], oggstream->header_len[0]);
+    oggstream->header[2] = av_memdup(header[2], oggstream->header_len[2]);
+    if (!oggstream->header[0] || !oggstream->header[2])
+        return AVERROR(ENOMEM);
+
+    p = ogg_write_vorbiscomment(7, s->flags & AVFMT_FLAG_BITEXACT,
+                                &oggstream->header_len[1], &st->metadata,
+                                framing_bit, NULL, 0);
+    oggstream->header[1] = p;
+    if (!p)
+        return AVERROR(ENOMEM);
+
+    bytestream_put_byte(&p, comment_type);
+    bytestream_put_buffer(&p, name, 6);
+
+    return 0;
+}
+
+extern const OGGMuxerMapping ff_ogg_flac_muxer_mapping;
+extern const OGGMuxerMapping ff_ogg_opus_muxer_mapping;
+extern const OGGMuxerMapping ff_ogg_speex_muxer_mapping;
+extern const OGGMuxerMapping ff_ogg_theora_muxer_mapping;
+extern const OGGMuxerMapping ff_ogg_vorbis_muxer_mapping;
+extern const OGGMuxerMapping ff_ogg_vp8_muxer_mapping;
+
 #endif /* AVFORMAT_OGG_MUXER_H */
diff --git a/libavformat/ogg/muxer/flac.c b/libavformat/ogg/muxer/flac.c
new file mode 100644
index 00000000000..78b63339b1e
--- /dev/null
+++ b/libavformat/ogg/muxer/flac.c
@@ -0,0 +1,77 @@
+/*
+ * Ogg FLAC muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavcodec/bytestream.h"
+#include "libavcodec/flac.h"
+#include "libavutil/mem.h"
+#include "libavformat/ogg/muxer.h"
+
+static int flac_build_headers(AVCodecParameters *par,
+                              OGGStreamContext *oggstream, int bitexact,
+                              AVDictionary **m)
+{
+    uint8_t *p;
+
+    if (par->extradata_size < FLAC_STREAMINFO_SIZE)
+        return AVERROR(EINVAL);
+
+    // first packet: STREAMINFO
+    oggstream->header_len[0] = 51;
+    oggstream->header[0] = av_mallocz(51); // per ogg flac specs
+    p = oggstream->header[0];
+    if (!p)
+        return AVERROR(ENOMEM);
+    bytestream_put_byte(&p, 0x7F);
+    bytestream_put_buffer(&p, "FLAC", 4);
+    bytestream_put_byte(&p, 1); // major version
+    bytestream_put_byte(&p, 0); // minor version
+    bytestream_put_be16(&p, 1); // headers packets without this one
+    bytestream_put_buffer(&p, "fLaC", 4);
+    bytestream_put_byte(&p, 0x00); // streaminfo
+    bytestream_put_be24(&p, 34);
+    bytestream_put_buffer(&p, par->extradata, FLAC_STREAMINFO_SIZE);
+
+    // second packet: VorbisComment
+    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0, 
NULL, 0);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[1] = p;
+    bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
+    bytestream_put_be24(&p, oggstream->header_len[1] - 4);
+
+    return 0;
+}
+
+static int flac_init(AVFormatContext *s, AVStream *st)
+{
+    int err = flac_build_headers(st->codecpar, st->priv_data,
+                                 s->flags & AVFMT_FLAG_BITEXACT,
+                                 &st->metadata);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
+    return err;
+}
+
+const OGGMuxerMapping ff_ogg_flac_muxer_mapping = {
+    .codec_id  = AV_CODEC_ID_FLAC,
+    .new_links = 1,
+    .init      = flac_init,
+};
diff --git a/libavformat/ogg/muxer/opus.c b/libavformat/ogg/muxer/opus.c
new file mode 100644
index 00000000000..bb37aeba305
--- /dev/null
+++ b/libavformat/ogg/muxer/opus.c
@@ -0,0 +1,85 @@
+/*
+ * Ogg Opus muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavcodec/bytestream.h"
+#include "libavcodec/opus/tab.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
+#include "libavformat/internal.h"
+#include "libavformat/ogg/muxer.h"
+
+#define OPUS_HEADER_SIZE 19
+
+static int opus_build_headers(AVCodecParameters *par,
+                              OGGStreamContext *oggstream, int bitexact,
+                              AVDictionary **m, AVChapter **chapters,
+                              unsigned int nb_chapters)
+{
+    uint8_t *p;
+
+    if (par->extradata_size < OPUS_HEADER_SIZE)
+        return AVERROR_INVALIDDATA;
+
+    /* first packet: Opus header */
+    p = av_mallocz(par->extradata_size);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[0] = p;
+    oggstream->header_len[0] = par->extradata_size;
+    bytestream_put_buffer(&p, par->extradata, par->extradata_size);
+
+    /* second packet: VorbisComment */
+    p = ogg_write_vorbiscomment(8, bitexact, &oggstream->header_len[1], m, 0, 
chapters, nb_chapters);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[1] = p;
+    bytestream_put_buffer(&p, "OpusTags", 8);
+
+    return 0;
+}
+
+static int opus_init(AVFormatContext *s, AVStream *st)
+{
+    int err;
+
+    avpriv_set_pts_info(st, 64, 1, OPUS_TIMESTAMP_RATE);
+    err = opus_build_headers(st->codecpar, st->priv_data,
+                             s->flags & AVFMT_FLAG_BITEXACT,
+                             &st->metadata, s->chapters, s->nb_chapters);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing Opus headers\n");
+    return err;
+}
+
+static int64_t opus_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+
+    /* The pre-skip of the link's OpusHead, in the 48 kHz time base. */
+    return pkt->pts + pkt->duration + AV_RL16(oggstream->header[0] + 10);
+}
+
+const OGGMuxerMapping ff_ogg_opus_muxer_mapping = {
+    .codec_id       = AV_CODEC_ID_OPUS,
+    .new_links      = 1,
+    .init           = opus_init,
+    .packet_granule = opus_packet_granule,
+};
diff --git a/libavformat/ogg/muxer/speex.c b/libavformat/ogg/muxer/speex.c
new file mode 100644
index 00000000000..3fea42810bd
--- /dev/null
+++ b/libavformat/ogg/muxer/speex.c
@@ -0,0 +1,69 @@
+/*
+ * Ogg Speex muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavcodec/bytestream.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
+#include "libavformat/ogg/muxer.h"
+
+#define SPEEX_HEADER_SIZE 80
+
+static int speex_build_headers(AVCodecParameters *par,
+                               OGGStreamContext *oggstream, int bitexact,
+                               AVDictionary **m)
+{
+    uint8_t *p;
+
+    if (par->extradata_size < SPEEX_HEADER_SIZE)
+        return AVERROR_INVALIDDATA;
+
+    // first packet: Speex header
+    p = av_mallocz(SPEEX_HEADER_SIZE);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[0] = p;
+    oggstream->header_len[0] = SPEEX_HEADER_SIZE;
+    bytestream_put_buffer(&p, par->extradata, SPEEX_HEADER_SIZE);
+    AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0
+
+    // second packet: VorbisComment
+    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0, 
NULL, 0);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[1] = p;
+
+    return 0;
+}
+
+static int speex_init(AVFormatContext *s, AVStream *st)
+{
+    int err = speex_build_headers(st->codecpar, st->priv_data,
+                                  s->flags & AVFMT_FLAG_BITEXACT,
+                                  &st->metadata);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
+    return err;
+}
+
+const OGGMuxerMapping ff_ogg_speex_muxer_mapping = {
+    .codec_id = AV_CODEC_ID_SPEEX,
+    .init     = speex_init,
+};
diff --git a/libavformat/ogg/muxer/theora.c b/libavformat/ogg/muxer/theora.c
new file mode 100644
index 00000000000..b283fa2e4f2
--- /dev/null
+++ b/libavformat/ogg/muxer/theora.c
@@ -0,0 +1,134 @@
+/*
+ * Ogg Theora muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavcodec/xiph.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/log.h"
+#include "libavutil/rational.h"
+#include "libavformat/internal.h"
+#include "libavformat/ogg/muxer.h"
+
+typedef struct TheoraMuxerContext {
+    int kfgshift; ///< width of the frame count since the last keyframe in the 
granule
+    int vrev;     ///< bitstream revision
+    int64_t last_kf_pts;
+} TheoraMuxerContext;
+
+static int theora_init(AVFormatContext *s, AVStream *st)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    TheoraMuxerContext *theora = oggstream->priv_data;
+    int den, num;
+    int err = ogg_build_xiph_headers(s, st, 42, 0x81, "theora", 0);
+
+    if (err < 0)
+        return err;
+
+    den = AV_RB32(oggstream->header[0] + 22);
+    num = AV_RB32(oggstream->header[0] + 26);
+    /* Make sure to use time base stored in the Theora stream header to write
+       correct timestamps */
+    if (st->time_base.num != num || st->time_base.den != den) {
+        av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
+               st->time_base.num, st->time_base.den, num, den);
+        avpriv_set_pts_info(st, 64, num, den);
+    }
+    /** KFGSHIFT is the width of the less significant section of the granule 
position
+        The less significant section is the frame count since the last 
keyframe */
+    theora->kfgshift = 
((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
+    theora->vrev = oggstream->header[0][9];
+    av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
+           theora->kfgshift, theora->vrev);
+
+    return 0;
+}
+
+/**
+ * Whether Theora headers set a frame rate other than the stream time base,
+ * which packets keep across links.
+ */
+static int theora_rate_changed(const AVStream *st, const uint8_t *extradata, 
size_t size)
+{
+    const uint8_t *header[3];
+    int header_len[3];
+
+    if (size > INT_MAX ||
+        avpriv_split_xiph_headers(extradata, size, 42, header, header_len) < 0)
+        return 0;
+    return av_cmp_q(st->time_base,
+                    (AVRational){ AV_RB32(header[0] + 26), AV_RB32(header[0] + 
22) }) != 0;
+}
+
+static const char *theora_new_link_refused(const AVStream *st, const AVPacket 
*pkt,
+                                           const uint8_t *new_extradata, 
size_t size)
+{
+    if (!new_extradata && !(pkt->flags & AV_PKT_FLAG_KEY))
+        return "New Theora links must start on a keyframe";
+    if (new_extradata && theora_rate_changed(st, new_extradata, size))
+        return "New Theora links cannot change the frame rate";
+    return NULL;
+}
+
+static int64_t theora_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    OGGStreamContext *oggstream = st->priv_data;
+    TheoraMuxerContext *theora = oggstream->priv_data;
+    int64_t pts = theora->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
+    int pframe_count;
+
+    if (pkt->flags & AV_PKT_FLAG_KEY)
+        theora->last_kf_pts = pts;
+    pframe_count = pts - theora->last_kf_pts;
+    // prevent frame count from overflow if key frame flag is not set
+    if (pframe_count >= (1<<theora->kfgshift)) {
+        theora->last_kf_pts += pframe_count;
+        pframe_count = 0;
+    }
+    return (theora->last_kf_pts<<theora->kfgshift) | pframe_count;
+}
+
+static int64_t theora_granule_to_timestamp(const AVStream *st, int64_t granule)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    const TheoraMuxerContext *theora = oggstream->priv_data;
+
+    return (granule>>theora->kfgshift) +
+        (granule & ((1<<theora->kfgshift)-1));
+}
+
+static int theora_key_granule(const AVStream *st, int64_t granule)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    const TheoraMuxerContext *theora = oggstream->priv_data;
+
+    return theora->kfgshift && !(granule & ((1<<theora->kfgshift)-1));
+}
+
+const OGGMuxerMapping ff_ogg_theora_muxer_mapping = {
+    .codec_id             = AV_CODEC_ID_THEORA,
+    .priv_data_size       = sizeof(TheoraMuxerContext),
+    .new_links            = 1,
+    .init                 = theora_init,
+    .new_link_refused     = theora_new_link_refused,
+    .packet_granule       = theora_packet_granule,
+    .granule_to_timestamp = theora_granule_to_timestamp,
+    .key_granule          = theora_key_granule,
+};
diff --git a/libavformat/ogg/muxer/vorbis.c b/libavformat/ogg/muxer/vorbis.c
new file mode 100644
index 00000000000..295b1c01ee3
--- /dev/null
+++ b/libavformat/ogg/muxer/vorbis.c
@@ -0,0 +1,33 @@
+/*
+ * Ogg Vorbis muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavformat/ogg/muxer.h"
+
+static int vorbis_init(AVFormatContext *s, AVStream *st)
+{
+    return ogg_build_xiph_headers(s, st, 30, 3, "vorbis", 1);
+}
+
+const OGGMuxerMapping ff_ogg_vorbis_muxer_mapping = {
+    .codec_id  = AV_CODEC_ID_VORBIS,
+    .new_links = 1,
+    .init      = vorbis_init,
+};
diff --git a/libavformat/ogg/muxer/vp8.c b/libavformat/ogg/muxer/vp8.c
new file mode 100644
index 00000000000..6ca93f5ea5b
--- /dev/null
+++ b/libavformat/ogg/muxer/vp8.c
@@ -0,0 +1,119 @@
+/*
+ * Ogg VP8 muxer mapping
+ * Copyright (c) 2007 Baptiste Coudurier <baptiste dot coudurier at free dot 
fr>
+ *
+ * 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
+ */
+
+#include "libavcodec/bytestream.h"
+#include "libavutil/dict.h"
+#include "libavutil/log.h"
+#include "libavutil/mem.h"
+#include "libavformat/internal.h"
+#include "libavformat/ogg/muxer.h"
+
+#define VP8_HEADER_SIZE 26
+
+static int vp8_build_headers(AVFormatContext *s, AVStream *st,
+                             OGGStreamContext *oggstream, int bitexact)
+{
+    AVCodecParameters *par = st->codecpar;
+    uint8_t *p;
+
+    /* first packet: VP8 header */
+    p = av_mallocz(VP8_HEADER_SIZE);
+    if (!p)
+        return AVERROR(ENOMEM);
+    oggstream->header[0] = p;
+    oggstream->header_len[0] = VP8_HEADER_SIZE;
+    bytestream_put_byte(&p, 0x4f); // HDRID
+    bytestream_put_buffer(&p, "VP80", 4); // Identifier
+    bytestream_put_byte(&p, 1); // HDRTYP
+    bytestream_put_byte(&p, 1); // VMAJ
+    bytestream_put_byte(&p, 0); // VMIN
+    bytestream_put_be16(&p, par->width);
+    bytestream_put_be16(&p, par->height);
+    bytestream_put_be24(&p, par->sample_aspect_ratio.num);
+    bytestream_put_be24(&p, par->sample_aspect_ratio.den);
+    if (st->r_frame_rate.num > 0 && st->r_frame_rate.den > 0) {
+        // OggVP8 requires pts to increase by 1 per visible frame, so use the 
least common
+        // multiple framerate if available.
+        av_log(s, AV_LOG_DEBUG, "Changing time base from %d/%d to %d/%d\n",
+               st->time_base.num, st->time_base.den,
+               st->r_frame_rate.den, st->r_frame_rate.num);
+        avpriv_set_pts_info(st, 64, st->r_frame_rate.den, 
st->r_frame_rate.num);
+    }
+    bytestream_put_be32(&p, st->time_base.den);
+    bytestream_put_be32(&p, st->time_base.num);
+
+    /* optional second packet: VorbisComment */
+    if (av_dict_count(st->metadata)) {
+        p = ogg_write_vorbiscomment(7, bitexact, &oggstream->header_len[1], 
&st->metadata, 0, NULL, 0);
+        if (!p)
+            return AVERROR(ENOMEM);
+        oggstream->header[1] = p;
+        bytestream_put_byte(&p, 0x4f); // HDRID
+        bytestream_put_buffer(&p, "VP80", 4); // Identifier
+        bytestream_put_byte(&p, 2); // HDRTYP
+        bytestream_put_byte(&p, 0x20);
+    }
+
+    return 0;
+}
+
+static int vp8_init(AVFormatContext *s, AVStream *st)
+{
+    int err = vp8_build_headers(s, st, st->priv_data,
+                                s->flags & AVFMT_FLAG_BITEXACT);
+    if (err)
+        av_log(s, AV_LOG_ERROR, "Error writing VP8 headers\n");
+    return err;
+}
+
+static int64_t vp8_packet_granule(AVStream *st, const AVPacket *pkt)
+{
+    const OGGStreamContext *oggstream = st->priv_data;
+    int64_t pts, invcnt, dist;
+    int visible;
+
+    visible = (pkt->data[0] >> 4) & 1;
+    pts     = pkt->pts + pkt->duration;
+    invcnt  = (oggstream->last_granule >> 30) & 3;
+    invcnt  = visible ? 3 : (invcnt == 3 ? 0 : invcnt + 1);
+    dist    = (pkt->flags & AV_PKT_FLAG_KEY) ? 0 : ((oggstream->last_granule 
>> 3) & 0x07ffffff) + 1;
+
+    return (pts << 32) | (invcnt << 30) | (dist << 3);
+}
+
+static int64_t vp8_granule_to_timestamp(const AVStream *st, int64_t granule)
+{
+    return granule >> 32;
+}
+
+static int vp8_key_granule(const AVStream *st, int64_t granule)
+{
+    return !((granule >> 3) & 0x07ffffff);
+}
+
+const OGGMuxerMapping ff_ogg_vp8_muxer_mapping = {
+    .codec_id             = AV_CODEC_ID_VP8,
+    .optional_extradata   = 1,
+    .init                 = vp8_init,
+    .packet_granule       = vp8_packet_granule,
+    .granule_to_timestamp = vp8_granule_to_timestamp,
+    .key_granule          = vp8_key_granule,
+};
-- 
2.54.1

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

Reply via email to