static OggPacket GetCommentPacket(MetadataDictionary metadata)
        {
            Contract.Requires(metadata != null);

            var comment = new VorbisComment();

            try
            {
                SafeNativeMethods.VorbisCommentInitialize(out comment);

                foreach (var item in new MetadataToVorbisCommentAdapter(metadata))
                {
                    // The key and value need to be marshaled as null-terminated UTF-8 strings:
                    var keyBytes = new byte[Encoding.UTF8.GetByteCount(item.Key) + 1];
                    Encoding.UTF8.GetBytes(item.Key, 0, item.Key.Length, keyBytes, 0);

                    var valueBytes = new byte[Encoding.UTF8.GetByteCount(item.Value) + 1];
                    Encoding.UTF8.GetBytes(item.Value, 0, item.Value.Length, valueBytes, 0);

                    SafeNativeMethods.VorbisCommentAddTag(ref comment, keyBytes, valueBytes);
                }

                OggPacket result;
                if (SafeNativeMethods.VorbisCommentHeaderOut(ref comment, out result) != 0)
                {
                    throw new IOException(Resources.MetadataEncoderHeaderOutError);
                }

                return(result);
            }
            finally
            {
                SafeNativeMethods.VorbisCommentClear(ref comment);
            }
        }