Metadata-Version: 2.1
Name: aws-cdk.aws-mediapackagev2-alpha
Version: 2.255.0a0
Summary: The CDK construct library for MediaPackageV2
Home-page: https://github.com/aws/aws-cdk
Author: Amazon Web Services
License: Apache-2.0
Project-URL: Source, https://github.com/aws/aws-cdk.git
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Typing :: Typed
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved
Classifier: Framework :: AWS CDK
Classifier: Framework :: AWS CDK :: 2
Requires-Python: ~=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: aws-cdk-lib<3.0.0,>=2.255.0
Requires-Dist: constructs<11.0.0,>=10.5.0
Requires-Dist: jsii<2.0.0,>=1.129.0
Requires-Dist: publication>=0.0.3
Requires-Dist: typeguard==2.13.3

# AWS::MediaPackageV2 Construct Library

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> 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](https://semver.org/) 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.

---
<!--END STABILITY BANNER-->

## 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](https://aws.amazon.com/mediapackage/).

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

```python
# 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

```python
# 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:

```python
# 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:

```python
# 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:

```python
# 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:

```python
# 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.

```python
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:

```python
# stack: Stack

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

You can also import from an ARN:

```python
# 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:

```python
# 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

```python
# 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:

```python
# 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:

```python
# 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:

```python
# 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"
        }
    }
))
```

## Granting Permissions

### Granting Ingest Access to MediaLive

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

```python
# 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:

```python
# 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:

```python
# 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

```python
# 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

```python
# 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

```python
# 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

```python
# 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:

```python
# 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](https://docs.aws.amazon.com/mediapackage/latest/userguide/manifest-filter-query-parameters.html).

| 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:

```python
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()`:

```python
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:

```python
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:

```python
# 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.

```python
# 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

```python
# 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

```python
# 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:

```python
# 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:

```python
# 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:

```python
# 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:

```python
# 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.
