From 287f777035d876754e6634704f759e6a42d85e8e Mon Sep 17 00:00:00 2001
From: Martijn van Beurden <mvanb1@gmail.com>
Date: Thu, 23 Jun 2022 12:01:32 +0200
Subject: [PATCH] Do not add channel mask to vorbis_comment that will be reused
 later

This fixes https://github.com/xiph/flac/issues/376
---
 src/flac/encode.c | 7 +++++--
 src/flac/encode.h | 1 +
 2 files changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/flac/encode.c b/src/flac/encode.c
index 5f616689..26812030 100644
--- a/src/flac/encode.c
+++ b/src/flac/encode.c
@@ -2044,13 +2044,16 @@ FLAC__bool EncoderSession_init_encoder(EncoderSession *e, encode_options_t optio
 		if(0 != static_metadata.cuesheet)
 			static_metadata_append(&static_metadata, static_metadata.cuesheet, /*needs_delete=*/false);
 		if(e->info.channel_mask) {
-			if(!flac__utils_set_channel_mask_tag(options.vorbis_comment, e->info.channel_mask)) {
+			options.vorbis_comment_with_channel_mask_tag = FLAC__metadata_object_clone(options.vorbis_comment);
+			if(!flac__utils_set_channel_mask_tag(options.vorbis_comment_with_channel_mask_tag, e->info.channel_mask)) {
 				flac__utils_printf(stderr, 1, "%s: ERROR adding channel mask tag\n", e->inbasefilename);
 				static_metadata_clear(&static_metadata);
 				return false;
 			}
+			static_metadata_append(&static_metadata, options.vorbis_comment_with_channel_mask_tag, /*needs_delete=*/true);
 		}
-		static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
+		else
+			static_metadata_append(&static_metadata, options.vorbis_comment, /*needs_delete=*/false);
 		for(i = 0; i < options.num_pictures; i++)
 			static_metadata_append(&static_metadata, options.pictures[i], /*needs_delete=*/false);
 		if(foreign_metadata) {
diff --git a/src/flac/encode.h b/src/flac/encode.h
index c0f36296..b0efda8a 100644
--- a/src/flac/encode.h
+++ b/src/flac/encode.h
@@ -88,6 +88,7 @@ typedef struct {
 	FLAC__bool limit_min_bitrate;
 
 	FLAC__StreamMetadata *vorbis_comment;
+	FLAC__StreamMetadata *vorbis_comment_with_channel_mask_tag;
 	FLAC__StreamMetadata *pictures[64];
 	unsigned num_pictures;