Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

AWS::MediaPackageV2 Construct Library

---

cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.


AWS Elemental MediaPackage V2

MediaPackage delivers high-quality video without concern for capacity and makes it easier to implement popular DVR features such as start over, pause, and rewind. Your content will be protected with comprehensive support for DRM. The service seamlessly integrates with other AWS media services as a complete set of tools for cloud-based video processing and delivery.

This package contains constructs for working with AWS Elemental MediaPackage V2. Allowing you to define AWS Elemental MediaPackage V2 Channel Groups, Channels, Origin Endpoints, Channel Policies and Origin Endpoint Policies.

For further information on AWS Elemental MediaPackage V2, see the documentation.

The following example creates an AWS Elemental MediaPackage V2 Channel Group, Channel and Origin Endpoint:

# stack: Stack

group = ChannelGroup(stack, "MyChannelGroup",
    channel_group_name="my-test-channel-group"
)

channel = Channel(stack, "MyChannel",
    channel_group=group,
    channel_name="my-testchannel",
    input=InputConfiguration.cmaf()
)

endpoint = OriginEndpoint(stack, "MyOriginEndpoint",
    channel=channel,
    origin_endpoint_name="my-test-endpoint",
    segment=Segment.cmaf(),
    manifests=[Manifest.hls(
        manifest_name="index"
    )]
)

Using Factory Methods

# stack: Stack


# Create a channel group
group = ChannelGroup(stack, "MyChannelGroup",
    channel_group_name="my-channel-group"
)

# Add a channel using the factory method
channel = group.add_channel("MyChannel",
    channel_name="my-channel",
    input=InputConfiguration.cmaf()
)

# Add an origin endpoint using the factory method
endpoint = channel.add_origin_endpoint("MyEndpoint",
    origin_endpoint_name="my-endpoint",
    segment=Segment.cmaf(),
    manifests=[Manifest.hls(manifest_name="index")]
)

Channel Group

A channel group is the top-level resource that consists of channels and origin endpoints associated with it.

The following code creates a Channel Group:

# stack: Stack

group = ChannelGroup(stack, "MyChannelGroup",
    channel_group_name="my-test-channel-group"
)

The following code imports an existing channel group using the name attribute:

# stack: Stack

channel_group = ChannelGroup.from_channel_group_attributes(stack, "ImportedChannelGroup",
    channel_group_name="MyChannelGroup"
)

You can also import from an ARN, which automatically extracts the name and region:

# stack: Stack

channel_group = ChannelGroup.from_channel_group_arn(stack, "ImportedChannelGroup", "arn:aws:mediapackagev2:us-west-2:123456789012:channelGroup/MyChannelGroup")

For cross-region imports, pass the region parameter to ensure the correct ARN is constructed:

# stack: Stack

channel_group = ChannelGroup.from_channel_group_attributes(stack, "ImportedChannelGroup",
    channel_group_name="MyChannelGroup",
    region="us-west-2"
)

Channel

A channel is part of a channel group and represents the entry point for a content stream into MediaPackage.

Input Configuration

Channels support two input types: HLS and CMAF.

from aws_cdk.aws_mediapackagev2_alpha import InputSwitchConfiguration
# stack: Stack
# group: ChannelGroup


hls_channel = Channel(stack, "HlsChannel",
    channel_group=group,
    input=InputConfiguration.hls()
)

cmaf_channel = Channel(stack, "CmafChannel",
    channel_group=group,
    input=InputConfiguration.cmaf(
        input_switch_configuration=InputSwitchConfiguration(
            mqcs_input_switching=True
        ),
        output_headers=[HeadersCMSD.MQCS]
    )
)

simple_cmaf_channel = Channel(stack, "SimpleCmafChannel",
    channel_group=group,
    input=InputConfiguration.cmaf(
        output_headers=[HeadersCMSD.MQCS]
    )
)

Importing an Existing Channel

The following code imports an existing channel using the name attributes:

# stack: Stack

channel = Channel.from_channel_attributes(stack, "ImportedChannel",
    channel_name="MyChannel",
    channel_group_name="MyChannelGroup"
)

You can also import from an ARN:

# stack: Stack

channel = Channel.from_channel_arn(stack, "ImportedChannel", "arn:aws:mediapackagev2:us-west-2:123456789012:channelGroup/MyGroup/channel/MyChannel")

Imported channels expose a region property, which is parsed from the ARN or falls back to the importing stack's region.

Channel Resource Policy

The following code creates a resource policy directly on the channel. This will automatically create a policy on the first call:

# channel: Channel

channel.add_to_resource_policy(PolicyStatement(
    sid="AllowMediaLiveRoleToAccessEmpChannel",
    principals=[ArnPrincipal("arn:aws:iam::AccountID:role/MediaLiveAccessRole")],
    effect=Effect.ALLOW,
    actions=["mediapackagev2:PutObject"],
    resources=[channel.channel_arn]
))

Origin Endpoint

# stack: Stack
# channel: Channel

OriginEndpoint(stack, "myendpoint",
    channel=channel,
    origin_endpoint_name="my-test-endpoint",
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index"
        )
    ]
)

The following code imports an existing origin endpoint using the name attributes:

# stack: Stack

origin_endpoint = OriginEndpoint.from_origin_endpoint_attributes(stack, "ImportedOriginEndpoint",
    channel_group_name="MyChannelGroup",
    channel_name="MyChannel",
    origin_endpoint_name="MyExampleOriginEndpoint"
)

You can also import from an ARN:

# stack: Stack

origin_endpoint = OriginEndpoint.from_origin_endpoint_arn(stack, "ImportedOriginEndpoint", "arn:aws:mediapackagev2:us-west-2:123456789012:channelGroup/MyGroup/channel/MyChannel/originEndpoint/MyEndpoint")

The following code creates a resource policy on the origin endpoint. This will automatically create a policy on the first call:

# origin: OriginEndpoint


origin.add_to_resource_policy(PolicyStatement(
    sid="AllowRequestsFromCloudFront",
    principals=[ServicePrincipal("cloudfront.amazonaws.com")],
    effect=Effect.ALLOW,
    actions=["mediapackagev2:GetHeadObject", "mediapackagev2:GetObject"],
    resources=[origin.origin_endpoint_arn],
    conditions={
        "StringEquals": {
            "aws:SourceArn": "arn:aws:cloudfront::123456789012:distribution/AAAAAAAAA"
        }
    }
))

CDN Authorization

MediaPackage V2 supports two ways to lock an origin endpoint to your CDN:

  • AWS Signature Version 4 (SigV4) — the CDN signs requests with an IAM role. For Amazon CloudFront, see CloudFront Integration. See the SigV4 authentication guide.
  • Header-based CDN authorization — the CDN attaches a shared secret in a request header that MediaPackage validates. Use this when your CDN doesn't support SigV4. See the CDN authorization guide.

To configure header-based authorization, set cdnAuth on the OriginEndpoint props. The L2 auto-creates the endpoint policy with:

  • a PolicyStatement requiring the mediapackagev2:RequestHasMatchingCdnAuthHeader condition on every GetObject request
  • the CdnAuthConfiguration block that references the secrets and the read role

If you don't supply a role, one is created with the needed Secrets Manager and KMS permissions.

from aws_cdk.aws_mediapackagev2_alpha import CdnAuthConfiguration
import aws_cdk.aws_secretsmanager as secretsmanager

# channel: Channel
# my_secret: secretsmanager.ISecret


OriginEndpoint(self, "OriginEndpoint",
    channel=channel,
    segment=Segment.ts(),
    manifests=[Manifest.hls(manifest_name="index")],
    cdn_auth=CdnAuthConfiguration(
        secrets=[my_secret]
    )
)

You can still call addToResourcePolicy() to add extra statements (e.g. a harvester allow); they're appended to the auto-created policy alongside the gating statement.

Granting Permissions

Granting Ingest Access to MediaLive

To allow AWS Elemental MediaLive to ingest content into a MediaPackage channel, use the grants.ingest() method:

# channel: Channel
# media_live_role: iam.IRole


# Grant MediaLive permission to ingest content
channel.grants.ingest(media_live_role)

CloudFront Integration

MediaPackage origin endpoints are designed to be used with Content Delivery Network (CDN) like Amazon CloudFront distributions. CloudFront provides caching, DDoS protection, and global content delivery for your streaming content.

The simplest way to connect CloudFront to a MediaPackage V2 endpoint is with MediaPackageV2Origin, which automatically creates an Origin Access Control (OAC) and wires the endpoint policy:

# endpoint: OriginEndpoint
# group: ChannelGroup


cloudfront.Distribution(self, "Distribution",
    default_behavior=cloudfront.BehaviorOptions(
        origin=MediaPackageV2Origin(endpoint,
            channel_group=group
        )
    )
)

This handles OAC creation, HTTPS-only origin config, and the IAM policy granting CloudFront access to the endpoint (including GetHeadObject for MQAR support).

For more control, you can manually configure the policy and OAC:

# origin_endpoint: OriginEndpoint
# distribution: cloudfront.Distribution


origin_endpoint.add_to_resource_policy(iam.PolicyStatement(
    sid="AllowCloudFrontServicePrincipal",
    principals=[iam.ServicePrincipal("cloudfront.amazonaws.com")],
    effect=iam.Effect.ALLOW,
    actions=["mediapackagev2:GetObject", "mediapackagev2:GetHeadObject"],
    resources=[origin_endpoint.origin_endpoint_arn],
    conditions={
        "StringEquals": {
            "aws:SourceArn": distribution.distribution_arn
        }
    }
))

Graduation plan: MediaPackageV2Origin currently lives in this alpha module. When MediaPackage V2 graduates to stable, it will move to aws-cloudfront-origins alongside S3BucketOrigin and other origin helpers.

Manifest Configuration

MediaPackage V2 supports multiple manifest formats: HLS, Low-Latency HLS (LL-HLS), DASH, and Microsoft Smooth Streaming (MSS).

HLS Manifests

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index",
            manifest_window=Duration.seconds(60),
            program_date_time_interval=Duration.seconds(60),
            scte_ad_marker_hls=AdMarkerHls.DATERANGE
        )
    ]
)

Low-Latency HLS Manifests

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.low_latency_hls(
            manifest_name="index",
            manifest_window=Duration.seconds(30),
            program_date_time_interval=Duration.seconds(5),
            child_manifest_name="child"
        )
    ]
)

DASH Manifests

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.dash(
            manifest_name="index",
            manifest_window=Duration.seconds(60),
            min_buffer_time=Duration.seconds(30),
            min_update_period=Duration.seconds(10),
            segment_template_format=SegmentTemplateFormat.NUMBER_WITH_TIMELINE,
            period_triggers=[DashPeriodTriggers.AVAILS, DashPeriodTriggers.DRM_KEY_ROTATION
            ]
        )
    ]
)

MSS Manifests

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.ism(),
    manifests=[
        Manifest.mss(
            manifest_name="index",
            manifest_window=Duration.seconds(60),
            manifest_layout=MssManifestLayout.COMPACT
        )
    ]
)

Multiple Manifests

You can configure multiple manifest formats for a single origin endpoint:

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(manifest_name="hls"),
        Manifest.dash(manifest_name="dash")
    ]
)
Segment type Supported manifests
Segment.cmaf() HLS, LL-HLS, DASH
Segment.ts() HLS, LL-HLS
Segment.ism() MSS

Each origin endpoint has a single segment configuration. If you need segments with different configurations, use multiple origin endpoints on the same channel.

@see https://docs.aws.amazon.com/mediapackage/latest/userguide/endpoints-create.html

Manifest Filtering

Manifest filters control which variants are included in the manifest. Filters are type-safe and validated against the MediaPackage manifest filtering rules.

Filter Method
Audio / video bitrate bitrate(), bitrateRange(), bitrateCombo()
Audio channels, sample rate, video height, framerate, trickplay height numeric(), numericList(), numericRange(), numericCombo()
Audio codec audioCodec(), audioCodecList()
Video codec videoCodec(), videoCodecList()
Video dynamic range videoDynamicRange(), videoDynamicRangeList()
Trickplay type trickplayType(), trickplayTypeList()
Audio / subtitle language text(), textList()
Advanced patterns custom()

The following example creates an HD streaming endpoint that serves only H.264/H.265 content between 1–5 Mbps with stereo audio in English or French:

from aws_cdk.aws_mediapackagev2_alpha import FilterConfiguration
# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index",
            filter_configuration=FilterConfiguration(
                manifest_filter=[
                    ManifestFilter.bitrate_range(BitrateFilterKey.VIDEO_BITRATE, Bitrate.mbps(1), Bitrate.mbps(5)),
                    ManifestFilter.numeric_range(NumericFilterKey.VIDEO_HEIGHT, 720, 1080),
                    ManifestFilter.video_codec_list([VideoCodec.H264, VideoCodec.H265]),
                    ManifestFilter.numeric(NumericFilterKey.AUDIO_CHANNELS, 2),
                    ManifestFilter.text_list(TextFilterKey.AUDIO_LANGUAGE, ["en-US", "fr"])
                ],
                time_delay=Duration.seconds(30)
            )
        )
    ]
)

For advanced patterns that combine ranges and single values, use numericCombo() or bitrateCombo():

from aws_cdk.aws_mediapackagev2_alpha import FilterConfiguration
# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index",
            filter_configuration=FilterConfiguration(
                manifest_filter=[
                    # video_height:240-360,720-1080,1440
                    ManifestFilter.numeric_combo(NumericFilterKey.VIDEO_HEIGHT, [
                        NumericExpression.range(240, 360),
                        NumericExpression.range(720, 1080),
                        NumericExpression.value(1440)
                    ])
                ]
            )
        )
    ]
)

DRM Settings

You can exclude session keys from HLS and LL-HLS multivariant playlists using the drmSettings filter configuration. This improves compatibility with legacy HLS clients and provides more granular access control:

from aws_cdk.aws_mediapackagev2_alpha import FilterConfiguration
# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index",
            filter_configuration=FilterConfiguration(
                drm_settings=[DrmSettingsKey.EXCLUDE_SESSION_KEYS]
            )
        )
    ]
)

Start Tag Configuration

Configure where playback should start in HLS and LL-HLS manifests using the EXT-X-START tag:

# channel: Channel


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[
        Manifest.hls(
            manifest_name="index",
            start_tag=StartTag.of(10)
        )
    ]
)

Segment Configuration

Configure segment settings for your origin endpoint.

# channel: Channel


OriginEndpoint(self, "TsEndpoint",
    channel=channel,
    segment=Segment.ts(
        duration=Duration.seconds(6),
        name="segment",
        include_dvb_subtitles=True,
        use_audio_rendition_group=True,
        include_iframe_only_streams=False,
        scte_filter=[ScteMessageType.BREAK, ScteMessageType.DISTRIBUTOR_ADVERTISEMENT
        ]
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

OriginEndpoint(self, "CmafEndpoint",
    channel=channel,
    segment=Segment.cmaf(
        duration=Duration.seconds(6),
        name="segment",
        include_iframe_only_streams=True,
        scte_filter=[ScteMessageType.DISTRIBUTOR_ADVERTISEMENT]
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(),
    manifests=[Manifest.hls(manifest_name="index")]
)

Encryption and DRM

Protect your content with encryption using SPEKE (Secure Packager and Encoder Key Exchange). Each container type has its own encryption class with type-safe options:

CMAF Encryption

# channel: Channel
# speke_role: iam.IRole


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(
        encryption=CmafEncryption.speke(
            method=CmafEncryptionMethod.CBCS,
            drm_systems=[CmafDrmSystem.FAIRPLAY, CmafDrmSystem.WIDEVINE],
            resource_id="my-content-id",
            url="https://example.com/speke",
            role=speke_role,
            key_rotation_interval=Duration.seconds(300),
            audio_preset=PresetSpeke20Audio.PRESET_AUDIO_2,
            video_preset=PresetSpeke20Video.PRESET_VIDEO_2
        )
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

TS Encryption

# channel: Channel
# speke_role: iam.IRole


OriginEndpoint(self, "TsEndpoint",
    channel=channel,
    segment=Segment.ts(
        encryption=TsEncryption.speke(
            method=TsEncryptionMethod.SAMPLE_AES,
            resource_id="my-content-id",
            url="https://example.com/speke",
            role=speke_role
        )
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

TS encryption defaults the DRM system based on the method: FairPlay for SAMPLE_AES, Clear Key AES 128 for AES_128. You can override this with the drmSystems property using TsDrmSystem.

Content Key Encryption

You can add content key encryption by providing a certificate imported into AWS Certificate Manager. Your DRM key provider must support content key encryption for this to work:

# channel: Channel
# speke_role: iam.IRole
# certificate: certificatemanager.ICertificate


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(
        encryption=CmafEncryption.speke(
            method=CmafEncryptionMethod.CBCS,
            drm_systems=[CmafDrmSystem.FAIRPLAY],
            resource_id="my-content-id",
            url="https://example.com/speke",
            role=speke_role,
            certificate=certificate
        )
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

Excluding Segment DRM Metadata

For CMAF content, you can exclude DRM metadata from segments:

# channel: Channel
# speke_role: iam.IRole


OriginEndpoint(self, "Endpoint",
    channel=channel,
    segment=Segment.cmaf(
        encryption=CmafEncryption.speke(
            method=CmafEncryptionMethod.CBCS,
            drm_systems=[CmafDrmSystem.FAIRPLAY],
            resource_id="my-content-id",
            url="https://example.com/speke",
            role=speke_role,
            exclude_segment_drm_metadata=True
        )
    ),
    manifests=[Manifest.hls(manifest_name="index")]
)

ISM (Smooth Streaming) Encryption

ISM endpoints use CENC encryption with PlayReady. Audio and video presets are always SHARED, and key rotation is not supported. The DRM system defaults to PlayReady:

# channel: Channel
# speke_role: iam.IRole


OriginEndpoint(self, "IsmEndpoint",
    channel=channel,
    segment=Segment.ism(
        encryption=IsmEncryption.speke(
            resource_id="my-content-id",
            url="https://example.com/speke",
            role=speke_role
        )
    ),
    manifests=[Manifest.mss(manifest_name="index")]
)

CloudWatch Metrics

MediaPackage V2 resources expose CloudWatch metrics for monitoring. You can create alarms and dashboards using these metrics:

# channel_group: ChannelGroup
# channel: Channel
# endpoint: OriginEndpoint


# Create a CloudWatch alarm on channel group egress bytes
alarm = channel_group.metric_egress_bytes().create_alarm(self, "HighEgress",
    threshold=1000,
    evaluation_periods=1
)

# Monitor channel ingress response time
channel.metric_ingress_response_time().create_alarm(self, "SlowIngress",
    threshold=1000,
    evaluation_periods=2
)

# Track origin endpoint request count
request_metric = endpoint.metric_egress_request_count(
    statistic="sum",
    period=Duration.minutes(5)
)

Available metrics include:

  • metricIngressBytes() - Bytes ingested
  • metricEgressBytes() - Bytes delivered
  • metricIngressResponseTime() - Ingress response time (average)
  • metricEgressResponseTime() - Egress response time (average)
  • metricIngressRequestCount() - Number of ingress requests
  • metricEgressRequestCount() - Number of egress requests

All metrics support standard CloudWatch metric options for customizing period, statistic, and dimensions.

Release files for aws-cdk.aws-mediapackagev2-alpha 2.270.0a0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aws-cdk.aws-mediapackagev2-alpha 2.270.0a0
File Size Uploaded
aws_cdk_aws_mediapackagev2_alpha-2.270.0a0.tar.gz 347.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for aws-cdk.aws-mediapackagev2-alpha 2.270.0a0
File Interpreter ABI Platform
aws_cdk_aws_mediapackagev2_alpha-2.270.0a0-py3-none-any.whl Python 3 none any Details

Total release size: 688.7 kB

Release files / aws_cdk_aws_mediapackagev2_alpha-2.270.0a0.tar.gz

Download URL aws_cdk_aws_mediapackagev2_alpha-2.270.0a0.tar.gz
Size 347.8 kB
Tags Source
SHA-256 checksum
How to use checksums
d062f6275d1161fca5839a99cf4be002f30886627e7fc876f3530dfcb1903048
BLAKE2b-256 checksum
How to use checksums
810666e1c7ec5fd4f5897eb29e712beefe97630551f9b5204df0d8c19ef600f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release files / aws_cdk_aws_mediapackagev2_alpha-2.270.0a0-py3-none-any.whl

Download URL aws_cdk_aws_mediapackagev2_alpha-2.270.0a0-py3-none-any.whl
Size 340.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
941d3e52b7a5f6280f4f4047e89ee82180095b20f84593a508921588f572721b
BLAKE2b-256 checksum
How to use checksums
ff6563d6a2269cfc21c16a5e8abcb74a73e00f61f646777abf247f12ff90243a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release history Release notifications | RSS feed

This release

2.270.0a0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page