How to generate HLS and DASH ABR outputs using CMAF

Definition of a CMAF

CMAF (Common Media Application Format) is a media delivery format that enables efficient HTTP-based streaming of audio and video content.

It standardizes media segments for both MPEG-DASH and HLS streaming protocols, allowing content providers to create a single set of media segments that work with both delivery methods.

  • Uses fragmented MP4 (fMP4) container format

  • Supports efficient encoding with independent segments

  • Enables low-latency streaming through chunked encoding and transfer

  • Reduces storage requirements by using a single media format for multiple streaming protocols

This guide will walk you through creating CMAF-compliant templates for generating adaptive bitrate (ABR) streams for HLS and DASH.

As explained above, by using CMAF, you can create a single set of media segments that are compatible with both HLS and DASH streaming protocols, significantly reducing storage requirements and simplifying your media delivery workflow.

How to generate a CMAF template

To create a CMAF template, follow these steps to configure the required parameters:

(1) Basic Settings

Template Name (template_name):

  • Set a unique name for the template to identify and manage it easily, e.g., "cmaf_abr_template".

Output Format (format):

  • Must be set to "cmaf" to comply with the CMAF standard.

Segment Type (seg_type):

  • Fixed as "fmp4", as fragmented MP4 is a core component of CMAF.

Segment Duration (seg_time):

  • Duration of each segment in seconds. The recommended default value is 10.

(2) Adaptive Streams (adaptive_streams)

Parameter Explanation:

  • Define multiple resolution and bitrate streams to support various devices and network conditions. Each stream should include the following parameters:
    • vcodec: Video codec format (e.g., "h264").

    • resolution: Video resolution (e.g., "720p", "480p").

    • quality: Video quality score (e.g., 5 for high quality, 4.5 for medium quality).

    • audio_bitrate: Audio bitrate (e.g., 64000 bps).

Example Configuration:

[
{
"vcodec": "h264",
"resolution": "720p",
"video_bitrate": 2000000,
"audio_bitrate": 64000
},
{
"vcodec": "h264",
"resolution": "480p",
"video_bitrate": 2000000,
"audio_bitrate": 64000
}
]
(3) Optional Parameters for Optimization

Audio Codec (acodec):

  • Set to "aac" (default value) for best compatibility.

Frame Rate (framerate):

  • Specify the frame rate (e.g., 25) to improve playback smoothness.

GOP Size (gop_size):

  • Define the size of the Group of Pictures (GOP) in seconds. A recommended value is 10.

Template Description (description):

  • Add a description of the template to specify its purpose, e.g., "CMAF ABR Streaming Template".

3. Example Code

Below is a complete Python example showing how to configure and send a request to create a CMAF template:

import requests
from typing import Optional, Dict, Any, List
def create_template(
api_key: str,
api_secret: str,
template_name: str,
adaptive_streams: List[Dict[str, Any]],
format: str = "cmaf",
acodec: str = "aac",
seg_time: int = 10,
seg_type: str = "fmp4",
framerate: Optional[int] = None,
gop_size: Optional[int] = None,
description: Optional[str] = None,
**kwargs
) -> bool:
"""
Create a streaming template with customizable parameters
Args:
api_key: Access Key ID for API authentication
api_secret: Access Key Secret for API authentication
template_name: Name of the template
adaptive_streams: List of dictionaries containing stream configurations
format: Output format (default: cmaf)
acodec: Audio codec (default: aac)
seg_time: Segment duration in seconds (default: 10)
seg_type: Segment type (default: fmp4)
framerate: Output frame rate
gop_size: GOP size in seconds
description: Optional description for the template
**kwargs: Additional optional parameters for the template
Returns:
bool: True if creation successful, False otherwise
"""
url = "https://api.visionular.com/vodencoding/v1/add_template"
headers = {
"Content-Type": "application/json",
"auth-type": "use-basic"
}
payload = {
"template_name": template_name,
"format": format,
"acodec": acodec,
"seg_time": seg_time,
"seg_type": seg_type,
"adaptive_streams": adaptive_streams,
**kwargs
}
if framerate:
payload["framerate"] = framerate
if gop_size:
payload["gop_size"] = gop_size
# Add description if provided
if description:
payload["description"] = description
try:
print("Sending request:", payload)
response = requests.post(
url,
headers=headers,
auth=(api_key, api_secret),
json=payload,
verify=True
)
# Print full response for debugging
print("Response status:", response.status_code)
print("Response headers:", response.headers)
print("Response content:", response.text)
response.raise_for_status()
result = response.json()
if result["code"] == 0:
print(f"Template '{template_name}' created successfully!")
return True
else:
print(f"Template creation failed: {result['msg']}")
return False
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e}")
print(f"Response content: {e.response.text if e.response else 'No response'}")
return False
except Exception as e:
print(f"Unexpected error: {e}")
return False
# Example usage
if __name__ == "__main__":
api_key = "54F6A8740DEE4710BD4C6CDD17F260ED"
api_secret = "69CB474C4F954BAF878BD4A59BC40461"
template_name = "cmaf_abr_api"
adaptive_streams = [
{
"vcodec": "h264",
"resolution": "720p",
"video_bitrate": 2000000,
"audio_bitrate": 64000
},
{
"vcodec": "h264",
"resolution": "480p",
"video_bitrate": 2000000,
"audio_bitrate": 64000
}
]
# Create the CMAF template
if create_template(
api_key=api_key,
api_secret=api_secret,
template_name=template_name,
adaptive_streams=adaptive_streams,
format="cmaf",
framerate=25,
gop_size=10,
description="cmaf_abr_api"
):
print("CMAF template created successfully!")
else:
print("Failed to create CMAF template.")