使用 Media Encoder Standard 自动生成比特率阶梯Use Media Encoder Standard to auto-generate a bitrate ladder

媒体服务徽标media services logo


概述Overview

本文介绍如何使用 Media Encoder Standard (MES) 根据输入分辨率和比特率自动生成比特率阶梯(比特率-分辨率对)。This article shows how to use Media Encoder Standard (MES) to auto-generate a bitrate ladder (bitrate-resolution pairs) based on the input resolution and bitrate. 自动生成的预设不会超过输入分辨率和比特率。The auto-generated preset will never exceed the input resolution and bitrate. 例如,如果输入在 3 Mbps 时为 720p,则输出最多会保持 720p,并且会以低于 3 Mbps 的速率开始。For example, if the input is 720p at 3 Mbps, output remains 720p at best, and will start at rates lower than 3 Mbps.

编码为仅流式处理Encoding for Streaming Only

如果打算将源视频编码为仅用于流式处理,则应在创建编码任务时使用“自适应流式处理”预设。If your intent is to encode your source video only for streaming, then you should use the "Adaptive Streaming" preset when creating an encoding task. 使用“自适应流式处理”预设时, MES 编码器会以智能方式为比特率阶梯设置一个上限。When using the Adaptive Streaming preset, the MES encoder will intelligently cap a bitrate ladder. 但是,用户无法控制编码成本,因为是由服务确定要使用的层数和分辨率。However, you will not be able to control the encoding costs, since the service determines how many layers to use and at what resolution. 可以在本文末尾看到 MES 生成的输出层示例,这些示例是使用“自适应流式处理”预设进行编码得来的 。You can see examples of output layers produced by MES as a result of encoding with the Adaptive Streaming preset at the end of this article. 输出资产包含无音频和视频交错的 MP4 文件。The output Asset contains MP4 files where audio and video is not interleaved.

编码为流式处理和渐进式下载Encoding for Streaming and Progressive Download

如果打算将源视频编码为用于流式处理以及生成可供渐进式下载的 MP4 文件,则应在创建编码任务时使用“内容自适应多比特率 MP4”预设。If your intent is to encode your source video for streaming as well as to produce MP4 files for progressive download, then you should use the "Content Adaptive Multiple Bitrate MP4" preset when creating an encoding task. 使用“内容自适应多比特率 MP4”预设时,MES 编码器将应用与上述相同的编码逻辑,但现在输出资产将包含音频和视频交叠的 MP4 文件 。When using the Content Adaptive Multiple Bitrate MP4 preset, the MES encoder applies the same encoding logic as above, but now the output asset will contain MP4 files where audio and video is interleaved. 可使用其中一个 MP4 文件(例如,最高比特率版本)作为渐进式下载文件。You can use one of these MP4 files (for example, the highest bitrate version) as a progressive download file.

使用媒体服务 .NET SDK 进行编码Encoding with Media Services .NET SDK

以下代码示例使用媒体服务 .NET SDK 执行下列任务:The following code example uses Media Services .NET SDK to perform the following tasks:

  • 创建编码作业。Create an encoding job.
  • 获取对 Media Encoder Standard 编码器的引用。Get a reference to the Media Encoder Standard encoder.
  • 向作业添加一个编码任务,指定使用“自适应流式处理”预设。 Add an encoding task to the job and specify to use the Adaptive Streaming preset.
  • 创建包含所编码资产的输出资产。Create an output asset that contains the encoded asset.
  • 添加事件处理程序以检查作业进度。Add an event handler to check the job progress.
  • 提交作业。Submit the job.

创建和配置 Visual Studio 项目Create and configure a Visual Studio project

设置开发环境,并根据使用 .NET 进行媒体服务开发中所述,在 app.config 文件中填充连接信息。Set up your development environment and populate the app.config file with connection information, as described in Media Services development with .NET.

示例Example

using System;
using System.Configuration;
using System.Linq;
using Microsoft.WindowsAzure.MediaServices.Client;
using System.Threading;

namespace AdaptiveStreamingMESPresest
{
    class Program
    {
        // Read values from the App.config file.
        private static readonly string _AADTenantDomain =
            ConfigurationManager.AppSettings["AMSAADTenantDomain"];
        private static readonly string _RESTAPIEndpoint =
            ConfigurationManager.AppSettings["AMSRESTAPIEndpoint"];
        private static readonly string _AMSClientId =
            ConfigurationManager.AppSettings["AMSClientId"];
        private static readonly string _AMSClientSecret =
            ConfigurationManager.AppSettings["AMSClientSecret"];

        // Field for service context.
        private static CloudMediaContext _context = null;

        static void Main(string[] args)
        {
            AzureAdTokenCredentials tokenCredentials =
                new AzureAdTokenCredentials(_AADTenantDomain,
                    new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret),
                    AzureEnvironments.AzureChinaCloudEnvironment);

            var tokenProvider = new AzureAdTokenProvider(tokenCredentials);

            _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider);

            // Get an uploaded asset.
            var asset = _context.Assets.FirstOrDefault();

            // Encode and generate the output using the "Adaptive Streaming" preset.
            EncodeToAdaptiveBitrateMP4Set(asset);

            Console.ReadLine();
        }

        static public IAsset EncodeToAdaptiveBitrateMP4Set(IAsset asset)
        {
            // Declare a new job.
            IJob job = _context.Jobs.Create("Media Encoder Standard Job");

            // Get a media processor reference, and pass to it the name of the 
            // processor to use for the specific task.
            IMediaProcessor processor = GetLatestMediaProcessorByName("Media Encoder Standard");

            // Create a task
            ITask task = job.Tasks.AddNew("Media Encoder Standard encoding task",
            processor,
            "Adaptive Streaming",
            TaskOptions.None);

            // Specify the input asset to be encoded.
            task.InputAssets.Add(asset);
            // Add an output asset to contain the results of the job. 
            // This output is specified as AssetCreationOptions.None, which 
            // means the output asset is not encrypted. 
            task.OutputAssets.AddNew("Output asset",
            AssetCreationOptions.None);

            job.StateChanged += new EventHandler<JobStateChangedEventArgs>(JobStateChanged);
            job.Submit();
            job.GetExecutionProgressTask(CancellationToken.None).Wait();

            return job.OutputMediaAssets[0];
        }
        private static void JobStateChanged(object sender, JobStateChangedEventArgs e)
        {
            Console.WriteLine("Job state changed event:");
            Console.WriteLine("  Previous state: " + e.PreviousState);
            Console.WriteLine("  Current state: " + e.CurrentState);
            switch (e.CurrentState)
            {
                case JobState.Finished:
                    Console.WriteLine();
                    Console.WriteLine("Job is finished. Please wait while local tasks or downloads complete...");
                    break;
                case JobState.Canceling:
                case JobState.Queued:
                case JobState.Scheduled:
                case JobState.Processing:
                    Console.WriteLine("Please wait...\n");
                    break;
                case JobState.Canceled:
                case JobState.Error:

                    // Cast sender as a job.
                    IJob job = (IJob)sender;

                    // Display or log error details as needed.
                    break;
                default:
                    break;
            }
        }
        private static IMediaProcessor GetLatestMediaProcessorByName(string mediaProcessorName)
        {
            var processor = _context.MediaProcessors.Where(p => p.Name == mediaProcessorName).
            ToList().OrderBy(p => new Version(p.Version)).LastOrDefault();

            if (processor == null)
                throw new ArgumentException(string.Format("Unknown media processor", mediaProcessorName));

            return processor;
        }
    }
}

输出Output

此部分显示 MES 生成的输出层的三个示例,是使用“自适应流式处理” 预设进行编码得来的。This section shows three examples of output layers produced by MES as a result of encoding with the Adaptive Streaming preset.

示例 1Example 1

高度为“1080”,帧速率为“29.970”的源生成 6 个视频层:Source with height "1080" and framerate "29.970" produces 6 video layers:

Layer 高度Height 宽度Width 比特率 (kbps)Bitrate(kbps)
11 10801080 19201920 67806780
22 720720 12801280 35203520
33 540540 960960 22102210
44 360360 640640 11501150
55 270270 480480 720720
66 180180 320320 380380

示例 2Example 2

高度为“720”,帧速率为“23.970”的源生成 5 个视频层:Source with height "720" and framerate "23.970" produces 5 video layers:

Layer 高度Height 宽度Width 比特率 (kbps)Bitrate(kbps)
11 720720 12801280 29402940
22 540540 960960 18501850
33 360360 640640 960960
44 270270 480480 600600
55 180180 320320 320320

示例 3Example 3

高度为“360”,帧速率为“29.970”的源生成 3 个视频层:Source with height "360" and framerate "29.970" produces 3 video layers:

Layer 高度Height 宽度Width 比特率 (kbps)Bitrate(kbps)
11 360360 640640 700700
22 270270 480480 440440
33 180180 320320 230230

媒体服务学习路径Media Services learning paths

媒体服务 v3(最新版本)Media Services v3 (latest)

查看最新版本的 Azure 媒体服务!Check out the latest version of Azure Media Services!

媒体服务 v2(旧版)Media Services v2 (legacy)

另请参阅See Also

媒体服务编码概述Media Services Encoding Overview