ApsaraVideo VOD e ApsaraVideo Live suportam múltiplos métodos de criptografia de vídeo. Este tópico descreve como usar o ApsaraVideo Player SDK para reproduzir vídeos criptografados com a criptografia proprietária da Alibaba Cloud, criptografia padrão HLS e criptografia DRM.
Visão geral da criptografia de vídeo
ApsaraVideo VOD oferece um mecanismo abrangente de segurança de conteúdo que inclui controle de acesso, assinatura de URL, autenticação remota, criptografia de vídeo e download seguro.
O Overview abrange todas as políticas de segurança disponíveis. A tabela a seguir compara os três métodos de criptografia de vídeo.
Política de segurança | Método | Benefício | Nível de segurança | Complexidade de implantação |
Criptografia de vídeo | Criptografia proprietária da Alibaba Cloud | ApsaraVideo VOD usa um algoritmo de criptografia proprietário para oferecer uma solução de criptografia de vídeo integrada entre cloud e dispositivo, garantindo a segurança dos links de transmissão. | Alto | Relativamente baixa. Basta realizar configurações simples e integrar o ApsaraVideo Player SDK. |
Criptografia HTTP Live Streaming (HLS) | A criptografia HLS usa AES-128 para criptografar o conteúdo de vídeo e é compatível com todos os players HLS. No entanto, as chaves estão sujeitas a roubo. | Alto | Alta. É necessário configurar um service de gerenciamento de chaves e um service de emissão de tokens, além de garantir a segurança dos links de transmissão. | |
DRM comercial | Suporte nativo a sistemas DRM comerciais, incluindo Apple FairPlay e Google Widevine. Esse método oferece alto nível de segurança e atende aos requisitos da maioria dos detentores de direitos autorais. | Alto | Alta. A cobrança é feita com base no número de chamadas de licença (para DRM de terceiros, consulte os padrões de faturamento aplicáveis). Basta integrar o ApsaraVideo Player SDK. |
Compatibilidade do ApsaraVideo Player SDK
Antes de usar o ApsaraVideo Player SDK for Web para reproduzir vídeos criptografados, consulte Browser compatibility e Feature compatibility. O ApsaraVideo Player SDK for Web pode reproduzir vídeos criptografados com a criptografia proprietária da Alibaba Cloud nos principais navegadores móveis. Na tabela a seguir, ✔️ indica compatível e ❌ indica incompatível.
Para garantir a compatibilidade, baixe o ApsaraVideo Player SDK mais recente na página SDK overview.
Observação: HLS usa o formato M3U8.
Client | Playback method | Proprietary cryptography (HLS) | License-based cryptography (HLS) | License-based cryptography (MP4) | Proprietary cryptography (live FLV) | HLS encryption | Alibaba Cloud DRM | Third-party DRM |
Web | UrlSource-based playback | ❌ | ❌ | ❌ | ❌ | ✔️ | ❌ | ✔️ |
VidAuth-based playback | ✔️ | ❌ | ❌ | ❌ | ✔️ | ❌ | ❌ | |
VidSts-based playback | ✔️ | ❌ | ❌ | ❌ | ✔️ | ✔️ | ❌ | |
UrlSource-based live streaming | ❌ | ❌ | ❌ | ❌ | ✔️ | ❌ | ✔️ | |
LiveStsSource-based live streaming | ✔️ | ❌ | ❌ | ❌ | ❌ | ✔️ | ❌ | |
Native (iOS/Android/Flutter) | UrlSource-based playback | ✔️ | ✔️ Requer ApsaraVideo Player SDK v6.17.0 ou posterior. | ✔️ Requer ApsaraVideo Player SDK v6.8.0 ou posterior. | ❌ | ✔️ | ❌ | ✔️ Requires ApsaraVideo Player SDK v7.8.0 or later. Not supported on Flutter. |
VidAuth-based playback | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ❌ | ❌ | |
VidSts-based playback | ✔️ | ✔️ | ❌ | ❌ | ✔️ | ✔️ Not supported on Flutter. | ❌ | |
UrlSource-based live streaming | ❌ | ❌ | ❌ | ❌ | ✔️ | ❌ | ✔️ Requires ApsaraVideo Player SDK v7.8.0 or later. Not supported on Flutter. | |
LiveStsSource-based live streaming | ✔️ | ✔️ | ❌ | ✔️ | ❌ | ✔️ Not supported on Flutter. | ❌ |
Visão geral de criptografia
Criptografia de vídeo Alibaba Cloud (criptografia privada)
A Alibaba Cloud Video Encryption (Private Encryption) criptografa os dados de vídeo de forma que permaneçam criptografados mesmo após o download, impedindo a redistribuição não autorizada e o hotlinking. Alibaba Cloud Video Encryption (Private Encryption).
O Alibaba Cloud Player SDK gerencia a descriptografia e as interações com o servidor. Você só precisa configure a transcodificação criptografada e integre o SDK.
A Alibaba Cloud Video Encryption (Private Encryption) é gratuita, mas a transcodificação de mídia é obrigatória para a criptografia e gera cobranças. Media transcoding billing.
Configure a criptografia privada
Para configurar a Alibaba Cloud Video Encryption, siga as instruções em How-to guide.
Limitações
A Alibaba Cloud Video Encryption (Private Encryption) oferece suporte à criptografia de vídeos nos formatos HLS, FLV e MP4. A reprodução desses vídeos é exclusiva para o Alibaba Cloud Player. Clientes web suportam apenas reprodução em HLS. Clientes nativos suportam reprodução em todos esses formatos.
Criptografia de vídeo Alibaba Cloud (criptografia privada baseada em licença)
A Alibaba Cloud Video Encryption (License-based Private Encryption) é construída sobre a Private Encryption e permite a reprodução diretamente a partir da URL do vídeo criptografado, melhorando a velocidade de inicialização. Essa solução é ideal para cenários de vídeos curtos e dramas em formato curto.
A Alibaba Cloud Video Encryption (License-based Private Encryption) é gratuita, mas a transcodificação de mídia é obrigatória para a criptografia e gera cobranças. Media transcoding billing.
Configure a criptografia privada baseada em licença
Para configurar a Alibaba Cloud Video Encryption, siga as instruções em How-to guide.
Limitações
A Alibaba Cloud Video Encryption (License-based Private Encryption) oferece suporte à criptografia de vídeos nos formatos HLS e MP4. A reprodução desses vídeos criptografados é exclusiva para o Alibaba Cloud Player.
Criptografia padrão HLS
A HLS Standard Encryption usa AES-128 para criptografar o conteúdo de vídeo. É compatível com todos os players HLS, incluindo os desenvolvidos internamente e os de código aberto, mas sua implementação é mais complexa e menos segura do que os métodos proprietários. HLS Standard Encryption.
A HLS Standard Encryption é gratuita, mas a transcodificação de mídia é obrigatória para a criptografia e gera cobranças. Media transcoding billing.
Configure a HLS Standard Encryption
Para configurar a HLS Standard Encryption, siga as instruções em Integration guide.
Limitações
A HLS Standard Encryption é compatível com diversos players HLS. Este tópico utiliza o Alibaba Cloud Player como exemplo. O Alibaba Cloud Player suporta a passagem de token — o CDN ajusta dinamicamente o URI de descriptografia no arquivo de manifesto HLS, adicionando um token de usuário que sua aplicação pode verifique.
Criptografia DRM Alibaba Cloud
O ApsaraVideo VOD suporta criptografia Digital Rights Management (DRM) conforme os padrões do setor, com os esquemas Widevine e FairPlay, oferecendo uma solução completa para o gerenciamento de vídeos protegidos por direitos autorais. DRM encryption.
A criptografia DRM é aplicada durante a transcodificação (taxas de transcodificação de mídia são cobradas). Taxas de licença DRM são aplicadas quando um cliente solicita uma licença de reprodução. DRM billing.
Configure a criptografia DRM
Ative este recurso nos consoles do ApsaraVideo Live e do ApsaraVideo VOD: Configure DRM encryption for ApsaraVideo Live e Configure DRM encryption for ApsaraVideo VOD.
Limitações
Atualmente, vídeos criptografados com DRM só podem ser reproduzidos com o Alibaba Cloud Player.
Criptografia DRM de terceiros
O ApsaraVideo VOD suporta criptografia DRM de terceiros, possibilitando um fluxo de trabalho completo — desde a produção de vídeo no ApsaraVideo for Media Processing, passando pela criptografia DRM de terceiros, até a reprodução com o Alibaba Cloud Player SDK.
A criptografia DRM é aplicada durante a transcodificação (taxas de transcodificação de mídia são cobradas). Taxas de licença DRM são aplicadas quando um cliente solicita uma licença de reprodução. DRM billing.
Configure a criptografia DRM
Ative este recurso no console do ApsaraVideo for Media Processing. Live Packaging e VOD Packaging.
Web client
-
Antes de usar o ApsaraVideo Player SDK for Web, verifique a compatibilidade do navegador com a criptografia proprietária do Alibaba Cloud.
O modo H5 é compatível com navegadores desktop e mobile. Feature support.
Por razões de segurança, a criptografia proprietária do Alibaba Cloud não permite depuração com vídeos criptografados reais.
Procedimento
Incorpore o player web à sua página.
Siga o guia Quick start para importar o ApsaraVideo Player SDK for Web na sua página.
-
Selecione um método de criptografia e inicie a reprodução.
O código a seguir demonstra como incorporar o player.
Criptografia proprietária do Alibaba Cloud
VOD (VidAuth)
Para reproduzir um vídeo criptografado com a criptografia proprietária do Alibaba Cloud usando o método VidAuth do ApsaraVideo VOD, você também deve passar o parâmetro encryptType: 1 para ativar a criptografia proprietária. Isso não é necessário para reproduzir vídeos padrão.
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
vid : '<your video ID>',// Required. The video ID. You can find this in the ApsaraVideo VOD console by choosing media library > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
playauth : '<your PlayAuth>',// Required. The playback credential. You can obtain this by calling the GetVideoPlayAuth operation.
encryptType: 1, // Required. Set this to 1 when playing streams with proprietary encryption. This parameter is not needed for other cases.
playConfig:{EncryptType:'AliyunVoDEncryption'}, // Required if your M3U8 stream also contains other streams that do not use proprietary encryption.
// authTimeout: 7200, // Optional. The validity period of the playback URL, in seconds. This value overrides the URL signing validity period set in the ApsaraVideo VOD console. If not specified, the default value is 7200. If set, ensure this value exceeds the video's duration to prevent the URL from expiring mid-playback.
},function(player){
console.log('The player is created.')
});
Live (LiveStsSource)
Para reproduzir uma transmissão ao vivo com criptografia proprietária usando o método LiveStsSource, forneça a URL do stream e uma credencial temporária STS. Para saber como gerar a credencial, consulte Obtain an STS token.
let player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isLive: true, // Set to true for live streaming.
source: '<your live stream url>',// Required. The playback URL of the HLS live stream with proprietary encryption.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
domain: '<your Domain>',// Required. The streaming domain for the live stream.
app:'<your App Name>',// Required. The AppName of the live stream.
stream:'<your Stream Name>',// Required. The StreamName of the original live stream, not a transcoded stream.If the stream name is mystream_lhd.m3u8, enter the mystream.
regionId: '<region of your video>',// Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
},function(player){
console.log('The player is created.')
});
-
Para reproduzir vídeos on-demand criptografados em navegadores no iOS com versão anterior à 17.1, implante um script de plugin adicional para o player. Siga estas etapas:
No iOS com versão anterior à 17.1, a criptografia proprietária requer um plugin baseado na tecnologia Service Worker. As políticas de segurança do navegador restringem os service workers a scripts de mesma origem, portanto, implante o plugin no mesmo domínio do seu site.
Baixe o script: https://g.alicdn.com/apsara-media-box/imp-web-player/<version_number>/aliplayer-worker-min.js
Implante o script: por exemplo, se o seu site de reprodução de vídeo for
https://www.aliyun.com/a/b.html, implante o script emhttps://www.aliyun.com/a/aliplayer-worker-min.js, ou seja, no mesmo diretório da página web.-
Passe esta URL ao inicializar o player:
new Aliplayer({ // ...other parameters swScriptURL: 'https://www.aliyun.com/a/aliplayer-worker-min.js' // Provide the full URL of the plugin script and ensure it is accessible. })
Observação: certifique-se de que a versão do player corresponda exatamente à versão do plugin.
Se sua página web for executada dentro de um aplicativo iOS empacotado de forma personalizada (como uni-app), adicione seu domínio ao
WKAppBoundDomainsno arquivoInfo.plistdo aplicativo para ativar o Service Worker noWKWebView. App-Bound Domains.
Criptografia padrão HLS
VOD (VidAuth)
Ao reproduzir um vídeo com criptografia padrão HLS usando o método VidAuth do ApsaraVideo VOD, caso o vídeo também possua outros streams sem criptografia padrão HLS ou streams transcodificados padrão, defina o parâmetro EncryptType como HLSEncryption para filtrar e reproduzir apenas o stream com criptografia padrão HLS.
let player = new Aliplayer({
id:'J_prismPlayer',
vid:'<your video ID>', // Required. The video ID. Example: 1e067a2831b641db90d570b6480f****.
playauth:'<your PlayAuth>', // Required. The video playback credential.
playConfig: { // Optional.
MtsHlsUriToken: '', // Optional. If you need to validate MtsHlsUriToken (user token), pass it in this parameter.
EncryptType: 'HLSEncryption', // Optional. If you set this parameter to HLSEncryption, only streams with HLS standard encryption are returned.
},
});
VOD (VidSts)
Ao reproduzir um vídeo com criptografia padrão HLS usando o método VidSts do ApsaraVideo VOD, caso o vídeo também possua outros streams sem criptografia padrão HLS ou streams transcodificados padrão, defina o parâmetro EncryptType como HLSEncryption para filtrar e reproduzir apenas o stream com criptografia padrão HLS.
let player = new Aliplayer({
id: 'J_prismPlayer',
vid : '<your video ID>', // Required. The video ID. You can obtain the ID from the ApsaraVideo VOD console (media library > Audio/Video) or by calling the SearchMedia API operation after the video is uploaded. Example: 1e067a2831b641db90d570b6480f****.
accessKeyId: '<your AccessKey ID>', // Required. The AccessKey ID of the STS temporary credential pair, returned when you generate the STS security token.
securityToken: '<your STS token>', // Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>', // Required. The AccessKey secret of the STS temporary credential pair, returned when you generate the STS security token.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
playConfig: { // Optional.
MtsHlsUriToken: '', // Optional. If you need to validate MtsHlsUriToken (user token), pass it in this parameter.
EncryptType: 'HLSEncryption', // Optional. If you set this parameter to HLSEncryption, only streams with HLS standard encryption are returned.
},
};
UrlSource
Ao reproduzir um stream ao vivo ou on-demand com criptografia padrão HLS usando o método UrlSource, nenhum parâmetro adicional é necessário. A configuração é idêntica à de um vídeo padrão.
let player = new Aliplayer({
id:'J_prismPlayer',
source:'<your play URL>', // The playback URL, which can be for a live or on-demand stream.
isLive: true, // Set to true for live streaming.
});
Criptografia DRM
VOD (VidSts)
Para reproduzir um vídeo criptografado com DRM usando o método VidSts do ApsaraVideo VOD, você também deve passar o parâmetro isDrm: true**.
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isDrm: true,
vid: '<your video ID>',// Required. The video ID. You can find this in the ApsaraVideo VOD console by choosing media library > Audio/Video. Example: 1e067a2831b641db90d570b6480f****.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
certId: '<your certificate ID>', // Required for playback on Apple devices. Use this parameter to request the Apple certificate. Obtain it from the ApsaraVideo VOD or ApsaraVideo Live console, depending on your DRM implementation.
// authTimeout: 7200, // Optional. The validity period of the playback URL, in seconds. This value overrides the URL signing validity period set in the ApsaraVideo VOD console. If not specified, the default value is 7200. If set, ensure this value exceeds the video's duration to prevent the URL from expiring mid-playback.
},function(player){
console.log('The player is created.')
});
Live (LiveStsSource)
Para reproduzir uma transmissão ao vivo criptografada com DRM usando o método LiveStsSource, forneça a URL do stream e uma credencial temporária STS. Para saber como gerar uma credencial temporária STS, consulte Obtain an STS token.
var player = new Aliplayer({
id: 'J_prismPlayer',
width: '100%',
isLive: true, // Set to true for live streaming.
isDrm: true,
source: '<your live stream url>',// Required. The playback URL of the DRM-encrypted live stream.
accessKeyId: '<your AccessKey ID>',// Required. The AccessKey ID of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
securityToken: '<your STS token>',// Required. The STS security token. Generate this by calling the STS AssumeRole operation.
accessKeySecret: '<your AccessKey Secret>',// Required. The AccessKey secret of the STS temporary credential pair. Generate this by calling the STS AssumeRole operation.
region: '<region of your video>', // Required. The service region, such as cn-shanghai, eu-central-1, or ap-southeast-1.
certId: '<your certificate ID>', // Required for playback on Apple devices. Use this parameter to request the Apple certificate. Obtain it from the ApsaraVideo VOD or ApsaraVideo Live console, depending on your DRM implementation.
},function(player){
console.log('The player is created.')
});
Android
Procedimento
Integre o Alibaba Cloud Player SDK para Android à sua aplicação. As seções a seguir apresentam as etapas e o código de exemplo.
-
Integre o Alibaba Cloud Player SDK para Android.
-
Crie um player para reproduzir um vídeo.
Siga Basic features. Para Step 3. Create a DataSource, escolha um dos métodos a seguir de acordo com seus requisitos.
Alibaba Cloud Video Encryption (criptografia privada)
Notas de uso
Vídeos HLS criptografados com Alibaba Cloud Video Encryption (criptografia privada) podem ser reproduzidos por URL após a transcodificação. Antes de transcodificar, vincule uma licença na mesma conta (Manage License), depois defina o parâmetro EncryptType ao create a transcoding template group. Exemplo:
Após criar o modelo, não o modifique nem salve no console. Caso contrário, o método de criptografia será sobrescrito.
[{
"TranscodeTemplateId": "",
"TemplateName": "740P H.264 HLS local encryption",
"Type": "Normal",
"Container": {
"Format": "m3u8"
},
"TransConfig": {
"IsCheckReso": false,
"IsCheckResoFail": false,
"IsCheckVideoBitrate": false,
"IsCheckVideoBitrateFail": false,
"IsCheckAudioBitrate": false,
"IsCheckAudioBitrateFail": false
},
"Definition": "HD",
"MuxConfig": {
"Segment": {
"Duration": 5
}
},
"EncryptSetting": {
"EncryptType": "AliyunVoDLicenseEncryption"
},
"Video": {
"Height": 720,
"Bitrate": 400,
"Codec": "H.264",
"Fps": 25,
"Gop": 250,
"Profile": "high"
},
"Audio": {
"Bitrate": 64,
"Codec": "AAC",
"Channels": 2,
"Samplerate": "44100"
}
}]
VidAuth
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando ApsaraVideo VOD VidAuth, se o vídeo também contiver streams com outros tipos de criptografia ou streams transcodificados sem criptografia, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set this parameter to AliyunVoDEncryption, only privately encrypted video streams are returned.
vidAuth.setPlayConfig(vidPlayerConfigGen);
vidAuth.setVid("your_video_id");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The PlayAuth, generated by calling the ApsaraVideo VOD GetVideoPlayAuth operation.
vidAuth.setRegion("your_region");// This parameter is deprecated in player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically resolves it. For earlier versions, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidAuth);
VidSts
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando ApsaraVideo VOD VidSts, se o vídeo também contiver streams com outros tipos de criptografia ou streams transcodificados sem criptografia, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
VidSts vidSts = new VidSts();
VidPlayerConfigGen vidPlayerConfigGen = new VidPlayerConfigGen();
vidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.AliyunVoDEncryption);// Optional. If you set this parameter to AliyunVoDEncryption, only privately encrypted video streams are returned.
vidSts.setPlayConfig(vidPlayerConfigGen);
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
LiveSts
Para reproduzir um stream ao vivo com criptografia privada em formato HLS ou FLV usando o objeto LiveSts do ApsaraVideo Live, passe a URL e uma credencial STS, e defina o tipo de criptografia de vídeo como AliEncryption. O exemplo a seguir demonstra como fazer isso:
-
Crie uma fonte de dados.
Passe
LiveStscomo a fonte de reprodução.// Create a LiveSts object and set EncryptionType to AliEncryption. LiveSts liveSts = new LiveSts(); liveSts.setUrl("<your live stream url>");// Required. The playback URL of the privately encrypted HLS live stream. liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setSecurityToken("<your STS token>");// Required. The security token. To obtain this, call the STS AssumeRole operation. liveSts.setDomain("<your Domain>");// Required. The streaming domain of the live stream. liveSts.setApp("<your App Name>");// Required. The AppName of the live stream. liveSts.setStream("<your Stream Name>");// Required. The StreamName of the live stream. liveSts.setEncryptionType(LiveSts.LiveEncryptionType.AliEncryption);// Required. Set the encryption type to AliEncryption. liveSts.setRegion("<region of your video>");// Required. The service region, such as cn-shanghai. // Set the playback source. aliPlayer.setDataSource(liveSts); // Prepare for playback. aliPlayer.prepare(); -
Monitore a invalidação do STS.
Durante a reprodução ao vivo com criptografia, a chave de criptografia pode ser rotacionada. Quando isso ocorre, o player usa a credencial STS para solicitar a nova chave. Monitore a validade da credencial STS, pois uma credencial inválida interrompe a reprodução.
mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() { @Override public AliPlayer.Status onVerifySts(StsInfo info) { if(info is valid){ return IPlayer.StsStatus.Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be asynchronous or synchronous. return IPlayer.StsStatus.Pending; } // If the info is invalid and a new STS credential cannot be obtained, we recommend stopping playback to prevent corrupted video output. mAliyunVodPlayer.stop(); return IPlayer.StsStatus.Invalid; } @Override public AliPlayer.Status onVerifyAuth(VidAuth auth) { return AliPlayer.Status.Valid; } });NotaApós obter com sucesso uma nova credencial STS, chame o método
updateLiveStsInfopara atualizá-la. Se não for possível obter uma nova credencial, recomendamos interromper a reprodução. Sem a atualização da credencial STS, o player continuará usando a credencial expirada para solicitar chaves. Caso a credencial se torne inválida, isso poderá causar falha na reprodução ou corrupção do vídeo.mAliyunVodPlayer.updateStsInfo(stsInfo);
Alibaba Cloud Video Encryption (criptografia privada baseada em licença)
Notas de uso
Vídeos HLS criptografados com Alibaba Cloud Video Encryption (criptografia privada baseada em licença) podem ser reproduzidos por URL após a transcodificação. Antes de transcodificar, vincule uma licença na mesma conta (Manage License), depois defina o parâmetro EncryptType ao create a transcoding template group. Exemplo:
Após criar o modelo, não o modifique nem salve no console. Caso contrário, o método de criptografia será sobrescrito.
[{
"TranscodeTemplateId": "",
"TemplateName": "740P H.264 HLS local encryption",
"Type": "Normal",
"Container": {
"Format": "m3u8"
},
"TransConfig": {
"IsCheckReso": false,
"IsCheckResoFail": false,
"IsCheckVideoBitrate": false,
"IsCheckVideoBitrateFail": false,
"IsCheckAudioBitrate": false,
"IsCheckAudioBitrateFail": false
},
"Definition": "HD",
"MuxConfig": {
"Segment": {
"Duration": 5
}
},
"EncryptSetting": {
"EncryptType": "AliyunVoDLicenseEncryption"
},
"Video": {
"Height": 720,
"Bitrate": 400,
"Codec": "H.264",
"Fps": 25,
"Gop": 250,
"Profile": "high"
},
"Audio": {
"Bitrate": 64,
"Codec": "AAC",
"Channels": 2,
"Samplerate": "44100"
}
}]
UrlSource
Apenas o Alibaba Cloud Player SDK para Android V6.8.0 e versões posteriores suportam a reprodução de vídeos MP4 com criptografia privada baseada em licença usando UrlSource. A partir da versão V6.17.0, também há suporte para vídeos HLS com criptografia privada baseada em licença (bitrate único e adaptativo).
Para reproduzir um vídeo HLS ou MP4 com criptografia privada baseada em licença usando UrlSource, chame a operação GetPlayInfo para obter a URL de reprodução do vídeo. Para URLs de MP4, acrescente etavirp_nuyila=1 à URL antes de passá-la ao player. Esse parâmetro pode ser inserido em qualquer posição na query string. Para HLS, use a URL original do vídeo. Configure o SDK do player da mesma forma que faria para um vídeo padrão; nenhum parâmetro adicional é necessário.
Exemplo de URL de reprodução 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Exemplo de URL de reprodução 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";
// Player
UrlSource urlSource = new UrlSource();
urlSource.setUri(playURL);// Required. The playback URL of the video. You can call the GetPlayInfo operation to obtain the URL.
aliPlayer.setDataSource(urlSource);
aliPlayer.prepare();
// Short video player
AliListPlayer aliyunListPlayer = AliPlayerFactory.createAliListPlayer(getApplicationContext());
// Add a UrlSource
aliyunListPlayer.addUrl(playURL,uid);
aliyunListPlayer.moveTo(uid);
// Preload
MediaLoader mediaLoader = MediaLoader.getInstance();
mediaLoader.load(playURL,"duration");
Criptografia HLS padrão
VidAuth
Ao reproduzir um vídeo com criptografia HLS padrão usando ApsaraVideo VOD VidAuth, se o vídeo também contiver outros streams com criptografia HLS não padrão ou streams transcodificados padrão, defina o tipo de criptografia como HLSEncryption para reproduzir apenas o stream com criptografia HLS padrão. O exemplo a seguir demonstra como fazer isso:
Se você ativou Rewrite standard HLS encryption M3U8 files, chame setMtsHlsUriToken para definir o token do usuário.
VidAuth vidAuth = new VidAuth();
VidPlayerConfigGen playerConfig = new VidPlayerConfigGen();
playerConfig.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);// Optional. If you set this parameter to HLSEncryption, only standard HLS encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Pass this parameter if you want to validate the MtsHlsUriToken (user token).
vidAuth.setPlayConfig(playerConfig);
vidAuth.setVid("your_video_id");// Required. The video ID.
vidAuth.setPlayAuth("<yourPlayAuth>");// Required. The PlayAuth, generated by calling the ApsaraVideo VOD GetVideoPlayAuth operation.
vidAuth.setRegion("your_region");// This parameter is deprecated in player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically resolves it. For earlier versions, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidAuth.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidAuth);
VidSts
Ao reproduzir um vídeo com criptografia HLS padrão usando ApsaraVideo VOD VidSts, se o vídeo também contiver outros streams com criptografia HLS não padrão ou streams transcodificados padrão, defina o tipo de criptografia como HLSEncryption para reproduzir apenas o stream com criptografia HLS padrão. O exemplo a seguir demonstra como fazer isso:
Se você ativou Rewrite standard HLS encryption M3U8 files, chame setMtsHlsUriToken para definir o token do usuário.
VidSts vidSts = new VidSts();
VidPlayerConfigGen playerConfig = new VidPlayerConfigGen();
VidPlayerConfigGen.setEncryptType(VidPlayerConfigGen.EncryptType.HLSEncryption);//Optional. If you set this parameter to HLSEncryption, only standard HLS encrypted video streams are returned.
playerConfig.setMtsHlsUriToken("token");// Optional. Pass this parameter if you want to validate the MtsHlsUriToken (user token).
vidSts.setPlayConfig(playerConfig);
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600);// Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
UrlSource
Para reproduzir um stream com criptografia HLS padrão usando UrlSource, configure o SDK do player da mesma forma que faria para um vídeo padrão.
Recomendamos usar o ApsaraVideo VOD. Chame a operação GetPlayInfo para obter a URL de reprodução do vídeo e passe-a ao player.
Se você ativou Rewrite standard HLS encryption M3U8 files, acrescente MtsHlsUriToken=<token> à URL do vídeo antes de passá-la ao player. Esse parâmetro pode ser inserido em qualquer posição na query string.
Exemplo de URL de reprodução original: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Exemplo de URL a ser passada ao player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
UrlSource urlSource = new UrlSource();
urlSource.setUri("playback_url");// The playback URL of the live or on-demand stream that uses standard HLS encryption.
aliPlayer.setDataSource(urlSource);
Criptografia DRM da Alibaba Cloud
No Android, recomendamos usar um SurfaceView para garantir a reprodução adequada de vídeos com alto nível de segurança.
VidSts
Primeiro, configure a criptografia DRM conforme descrito em Configure DRM encryption for ApsaraVideo VOD. Ao reproduzir um vídeo com criptografia DRM usando o ApsaraVideo VOD VidSts, a configuração é idêntica à de um vídeo sem criptografia. Nenhum parâmetro adicional é necessário.
VidSts vidSts = new VidSts();
vidSts.setVid("your_video_id");// Required. The video ID.
vidSts.setAccessKeyId("<yourAccessKeyId>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setAccessKeySecret("<yourAccessKeySecret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation.
vidSts.setSecurityToken("<yourSecurityToken>");// Required. The security token. To obtain this, call the STS AssumeRole operation.
vidSts.setRegion("your_region");// Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// vidSts.setAuthTimeout(3600); // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is set on the ApsaraVideo VOD console. The default value is 3600. If you set this parameter, ensure its value is greater than the video's duration to prevent the URL from expiring before playback is complete.
aliPlayer.setDataSource(vidSts);
LiveSts
Primeiro, configure a criptografia DRM conforme descrito em Configure DRM encryption for ApsaraVideo Live. Para reproduzir uma transmissão ao vivo com criptografia DRM usando o objeto LiveSts, passe a URL e uma credencial STS, além de definir o tipo de criptografia de vídeo como WideVine_FairPlay. O código a seguir fornece um exemplo:
-
Crie uma fonte de dados.
Passe
LiveStscomo a source de reprodução.// Create a LiveSts object and set EncryptionType to WideVine_FairPlay. LiveSts liveSts = new LiveSts(); liveSts.setUrl("<your live stream url>");// Required. The playback URL of the DRM-encrypted HLS live stream. liveSts.setAccessKeyId("<your AccessKey ID>");// Required. The AccessKey ID of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setAccessKeySecret("<your AccessKey Secret>");// Required. The AccessKey Secret of the temporary STS credential. To obtain this, call the STS AssumeRole operation. liveSts.setSecurityToken("<your STS token>");// Required. The security token. To obtain this, call the STS AssumeRole operation. liveSts.setDomain("<your Domain>");// Required. The streaming domain of the live stream. liveSts.setApp("<your App Name>");// Required. The AppName of the live stream. liveSts.setStream("<your Stream Name>");// Required. The StreamName of the live stream. liveSts.setEncryptionType(LiveSts.LiveEncryptionType.WideVine_FairPlay);// Required. Set the encryption type to WideVine_FairPlay. liveSts.setRegion("<region of your video>");// Required. The service region, such as cn-shanghai. // Set the playback source. aliPlayer.setDataSource(liveSts); // Prepare for playback. aliPlayer.prepare(); -
Monitore a invalidação do STS.
Durante a reprodução ao vivo com criptografia, a chave de criptografia pode ser rotacionada. Quando ocorre uma rotação de chave, o player usa a credencial STS para solicitar a nova chave. Monitore a validade da credencial STS, pois uma credencial inválida interrompe a reprodução.
mAliyunVodPlayer.setOnVerifyTimeExpireCallback(new AliPlayer.OnVerifyTimeExpireCallback() { @Override public AliPlayer.Status onVerifySts(StsInfo info) { if(info is valid){ return IPlayer.StsStatus.Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be asynchronous or synchronous. return IPlayer.StsStatus.Pending; } // If the info is invalid and a new STS credential cannot be obtained, we recommend stopping playback to prevent corrupted video output. mAliyunVodPlayer.stop(); return IPlayer.StsStatus.Invalid; } @Override public AliPlayer.Status onVerifyAuth(VidAuth auth) { return AliPlayer.Status.Valid; } });NotaApós obter uma nova credencial STS com sucesso, chame o método
updateLiveStsInfopara atualizá-la. Caso não consiga obter uma nova credencial, recomendamos interromper a reprodução. Se a credencial STS não for atualizada, o player continuará usando a credencial antiga para solicitar chaves após sua expiração. Uma credencial STS inválida pode causar falha na reprodução ou saída de vídeo corrompida.mAliyunVodPlayer.updateStsInfo(stsInfo);
Criptografia DRM de terceiros
Este recurso requer o player SDK V7.8.0 ou posterior.
UrlSource
Este recurso oferece suporte apenas ao esquema Widevine DRM para os protocolos HLS e DASH.
Primeiro, consulte VOD packaging para configurar a criptografia DRM. Ao reproduzir um vídeo com criptografia DRM pelo método UrlSource, além das configurações de um vídeo normal, implemente também a interface DrmCallback para obter as informações de chave do vídeo.
// Implement the DrmCallback.requestKey interface to obtain the key by following the documentation of your third-party DRM provider.
// The following example shows how to retrieve a key from PallyCon. For more information, see https://pallycon.com/docs/en/multidrm.
player.setDrmCallback(new DrmCallback() {
@Override
public byte[] requestKey(byte[] data) {
// Request the key information by using an HTTP POST request, as required by the DRM provider.
String licenseUrl = "https://license-global.pallycon.com/ri/licenseManager.do";
String[] header = {
// Replace TOKEN_ID with your own.
"pallycon-customdata-v2: TOKEN_ID"
};
// Avoid blocking this thread for too long.
byte[] response = async_http_post(licenseUrl, header, data);
if (response != null) {
// If the response_format of the token is set to 'original', return the response directly. Otherwise, you must parse the response before returning it.
// For more information, see https://pallycon.com/docs/en/multidrm/license/license-token/#token-json.
// The format and structure of the response can vary significantly between providers. Review it carefully. If the response cannot be used for decryption, the player reports an error through the onError callback.
return response;
} else {
// Handle exceptions. The player calls onError and reports the relevant error.
return null;
}
}
});
iOS
Procedimento
Integre o Player SDK para iOS ao seu aplicativo. As etapas e os exemplos de código são os seguintes:
-
Integre o Player SDK para iOS.
-
Crie um player para carregar e reproduzir vídeos.
Siga Basic Features. Em Step 3. Create a data source, utilize um dos métodos a seguir conforme suas necessidades.
Criptografia privada da Alibaba Cloud
VidAuth for VOD
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando o método VidAuth do ApsaraVideo VOD, se o vídeo também tiver streams não criptografados ou transcodificados no padrão, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Your video ID"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can obtain this credential by calling the GetVideoPlayAuth operation of ApsaraVideo VOD.
authSource.region = @"Your region"; // This parameter is deprecated in Player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically parses it. For SDK versions earlier than 5.5.5.0, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only privately encrypted video streams are returned.
authSource.playConfig = [config generatePlayerConfig];
[self.player setAuthSource:authSource];
VidSts for VOD
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando o método VidSts do ApsaraVideo VOD, se o vídeo também tiver streams não criptografados ou transcodificados no padrão, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Your video ID"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"AliyunVoDEncryption"]; // Optional. If you set the encryption type to AliyunVoDEncryption, only privately encrypted video streams are returned.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setStsSource:source];
LiveStsSource for live
Para reproduzir um stream ao vivo com criptografia privada em formato HLS ou FLV usando o método LiveStsSource, forneça a URL do stream e uma credencial STS, e defina o tipo de criptografia do vídeo como ENCRYPTION_TYPE_ALIVODENCRYPTION. O código a seguir apresenta um exemplo:
-
Crie uma fonte de dados.
Passe
AVPLiveStsSourcecomo source de reprodução.// Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_ALIVODENCRYPTION. AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live stream URL" accessKeyId:@"Temporary AccessKey ID" accessKeySecret:@"Temporary AccessKey secret" securityToken:@"Security token" region:@"Region value" domain:@"Streaming domain for the URL" app:@"Application name for streaming" stream:@"Stream name for streaming" encryptionType:ENCRYPTION_TYPE_ALIVODENCRYPTION];// Required. Set the encryption type to ENCRYPTION_TYPE_ALIVODENCRYPTION. // Set the playback source. [self.aliPlayer setLiveStsSource:liveStsSource]; ...... // Prepare for playback. [self.aliPlayer prepare]; -
Monitore a invalidação da credencial STS.
Durante a reprodução ao vivo com criptografia, a chave de criptografia pode ser rotacionada. Quando isso ocorre, o player usa a credencial STS para solicitar a nova chave. Monitore a validade da credencial, pois uma credencial inválida interrompe a reprodução.
__weak typeof(self) weakSelf = self; [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) { if (info is valid) { return Valid; } if (a valid STS credential can be obtained) { getSTS(); // This can be an asynchronous or synchronous operation. return Pending; } [weakSelf.aliPlayer stop]; return Invalid; }];NotaApós obter uma nova credencial STS, chame o método
updateLiveStsInfopara atualizá-la. Caso a tentativa de obter uma nova credencial falhe, recomendamos interromper a reprodução. Se a credencial STS não for atualizada, o player tentará usar a credencial expirada para solicitar a chave, o que pode causar artefatos visuais ou falha na reprodução.[self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];
Criptografia privada baseada em licença da Alibaba Cloud
UrlSource for VOD
Somente o Player SDK para iOS V6.8.0 e versões posteriores suportam a reprodução de vídeos MP4 com criptografia privada baseada em licença usando UrlSource. A versão V6.17.0 e posteriores suportam vídeos HLS com criptografia privada baseada em licença em bitrates simples e adaptativos.
Para reproduzir um vídeo HLS ou MP4 com criptografia privada baseada em licença usando o método UrlSource, chame a operação GetPlayInfo para obter a URL de reprodução do vídeo. Após obter a URL do vídeo, acrescente o parâmetro etavirp_nuyila=1 à URL antes de passá-la ao player. Esse parâmetro pode ser inserido em qualquer posição na query string. Ele é obrigatório apenas para vídeos MP4. Para vídeos HLS, use a URL original do vídeo. A configuração do player é a mesma utilizada para reprodução de vídeos padrão. Nenhum parâmetro adicional é necessário.
Exemplo de URL de reprodução 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Exemplo de URL de reprodução 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL
NSString *playURL = @"https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1";
// Player
AliPlayer *player = [[AliPlayer alloc] init];
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:playURL]; // Required. The playback URL of the video. You can call the GetPlayInfo operation to obtain the URL. For MP4 videos, you must append `etavirp_nuyila=1` to the URL. Example: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
[player setUrlSource:urlSource];
[player prepare];
// List player
AliListPlayer *listPlayer = [[AliListPlayer alloc] init];
[listPlayer addUrlSource:playURL uid:UUIDString];
[listPlayer moveTo:@"uid"];
// Preload
AliMedialoader *mediaLoader = [AliMediaLoader shareInstance];
[mediaLoader load:playURL duration:1000];
Criptografia padrão HLS
VidAuth for VOD
Ao reproduzir um vídeo criptografado com criptografia padrão HLS pelo método VidAuth do ApsaraVideo VOD, caso o vídeo também possua streams não criptografados ou transcodificados no padrão, defina o tipo de criptografia como HLSEncryption para reproduzir somente o stream com criptografia padrão HLS. Veja o exemplo de código a seguir:
Se você ativou M3U8 standard encryption rewriting, chame setHlsUriToken para definir o token do usuário.
AVPVidAuthSource *authSource = [[AVPVidAuthSource alloc] init];
authSource.vid = @"Your video ID"; // Required. The video ID.
authSource.playAuth = @"<yourPlayAuth>"; // Required. The playback credential. You can obtain this credential by calling the GetVideoPlayAuth operation of ApsaraVideo VOD.
authSource.region = @"Your region"; // This parameter is deprecated in Player SDK V5.5.5.0 and later. You do not need to set the region because the player automatically parses it. For SDK versions earlier than 5.5.5.0, this parameter is required. It specifies the region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
// authSource.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set this parameter to HLSEncryption, only video streams that are encrypted by using HLS standard encryption are returned.
[config setHlsUriToken: @"token"]; // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setAuthSource:authSource];
VidSts for VOD
Ao reproduzir um vídeo criptografado com criptografia padrão HLS pelo método VidSts do ApsaraVideo VOD, caso o vídeo também possua streams não criptografados ou transcodificados no padrão, defina o tipo de criptografia como HLSEncryption para reproduzir somente o stream com criptografia padrão HLS. Veja o exemplo de código a seguir:
Se você ativou M3U8 standard encryption rewriting, chame setHlsUriToken para definir o token do usuário.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.vid = @"Your video ID"; // Required. The video ID.
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Build the config by using VidPlayerConfigGenerator.
VidPlayerConfigGenerator* config = [[VidPlayerConfigGenerator alloc]init];
[config addVidPlayerConfigByStringValue:@"EncryptType" value:@"HLSEncryption"]; // Optional. If you set this parameter to HLSEncryption, only video streams that are encrypted by using HLS standard encryption are returned.
[config setHlsUriToken: @"token"]; // Optional. Use this parameter to pass the MtsHlsUriToken (user token) for verification.
source.playConfig = [config generatePlayerConfig];
// Set the playback source.
[self.player setStsSource:source];
UrlSource
Ao usar o método UrlSource para reproduzir um stream com criptografia padrão HLS, a configuração do player é idêntica à de reprodução de um vídeo padrão. Nenhum parâmetro adicional é necessário.
Recomendamos o uso do ApsaraVideo VOD. Chame a operação GetPlayInfo para obter a URL de reprodução do vídeo e passe-a ao player.
Se você ativou M3U8 standard encryption rewriting, acrescente MtsHlsUriToken=<token> à URL do vídeo antes de passá-la ao player. Esse parâmetro pode ser inserido em qualquer posição da query string.
Exemplo de URL de reprodução original: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Exemplo de URL a ser inserida no player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
AVPUrlSource *urlSource = [[AVPUrlSource alloc] urlWithString:url]; // The playback URL of the live or on-demand stream with HLS standard encryption.
[self.player setUrlSource:urlSource];
Criptografia Alibaba Cloud DRM
Na plataforma iOS, é necessário fazer uma chamada global única ao método setFairPlayCertID em AliPlayerGlobalSettings antes de [self.player prepare] para definir o ID do certificado. O ID do certificado pode ser obtido em ApsaraVideo VOD console > Configuration Management > Media Processing Configuration > DRM Certificate Management.
[AliPlayerGlobalSettings setFairPlayCertID:@"Your certificate ID obtained from the console"];
VidSts for VOD
Primeiro, consulte Configure DRM Encryption for VOD para configurar a criptografia DRM. Ao reproduzir um vídeo com criptografia DRM pelo método VidSts do ApsaraVideo VOD, a configuração é idêntica à de reprodução de um vídeo padrão. Nenhum parâmetro adicional é necessário.
AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
source.region = @"Your region"; // Required. The region where ApsaraVideo VOD is activated. Default value: cn-shanghai.
source.vid = @"Your video ID"; // Required. The video ID.
source.securityToken = @"<yourSecurityToken>"; // Required. The security token. You can obtain this token by calling the AssumeRole operation of STS.
source.accessKeySecret = @"<yourAccessKeySecret>"; // Required. The AccessKey secret of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
source.accessKeyId = @"<yourAccessKeyId>"; // Required. The AccessKey ID of the temporary STS credential. You can obtain this credential by calling the AssumeRole operation of STS.
// source.authTimeout = 3600; // Optional. The validity period of the playback URL in seconds. This value overrides the validity period of URL authentication that is configured in the ApsaraVideo VOD console. If you do not set this parameter, the default value 3600 is used. If you set this parameter, make sure that its value is greater than the actual video duration to prevent the playback URL from expiring before the playback is complete.
// Set the playback source.
[self.player setStsSource:source]
LiveStsSource for live
Primeiro, consulte Configure DRM Encryption for Live Streaming para configurar a criptografia DRM. Para reproduzir um stream ao vivo com criptografia DRM pelo método LiveStsSource, forneça a URL do stream e uma credencial STS, e defina o tipo de criptografia do vídeo como ENCRYPTION_TYPE_FAIRPLAY. Veja o exemplo de código a seguir:
-
Crie uma fonte de dados.
Passe
AVPLiveStsSourcecomo source de reprodução.// Create a LiveSts object and set encryptionType to ENCRYPTION_TYPE_FAIRPLAY. AVPLiveStsSource *liveStsSource = [[AVPLiveStsSource alloc] initWithUrl:@"Encrypted live stream URL" accessKeyId:@"Temporary AccessKey ID" accessKeySecret:@"Temporary AccessKey secret" securityToken:@"Security token" region:@"Region value" domain:@"Streaming domain for the URL" app:@"Application name for streaming" stream:@"Stream name for streaming" encryptionType:ENCRYPTION_TYPE_FAIRPLAY];// Required. Set the encryption type to ENCRYPTION_TYPE_FAIRPLAY. // Set the playback source. [self.aliPlayer setLiveStsSource:liveStsSource]; ...... // Prepare for playback. [self.aliPlayer prepare]; -
Monitore a invalidação da credencial STS.
Durante a reprodução ao vivo com criptografia, a chave de criptografia pode ser rotacionada. Quando isso ocorre, o player usa a credencial STS para solicitar a nova chave. É necessário monitorar a validade da credencial, pois uma credencial inválida interrompe a reprodução.
__weak typeof(self) weakSelf = self; [self.aliPlayer setVerifyStsCallback:^AVPStsStatus(AVPStsInfo info) { if (info is valid){ return Valid; } if(a valid STS credential can be obtained){ getSTS(); // This can be an asynchronous or synchronous operation. return Pending; } [weakSelf.aliPlayer stop]; return Invalid; }];NotaApós obter uma nova credencial STS, chame o método
updateLiveStsInfopara atualizá-la. Se a tentativa de obter uma nova credencial falhar, recomendamos interromper a reprodução. Caso a credencial STS não seja atualizada, o player tentará usar a credencial expirada para solicitar a chave, o que pode causar artefatos visuais ou falha na reprodução.[self.aliPlayer updateLiveStsInfo:self.liveStsSource.accessKeyId accKey:self.liveStsSource.accessKeySecret token:self.liveStsSource.securityToken region:self.liveStsSource.region];
Criptografia DRM de terceiros
Este recurso requer o Player SDK V7.8.0 ou posterior.
Use o AppleAVPlayer para reproduzir vídeos criptografados com FairPlay. Antes de iniciar a reprodução, chame
[self.player setPreferPlayerName:@"AppleAVPlayer"]para alternar o núcleo do player. Ao reproduzir vídeos sem criptografia DRM, chame[self.player setPreferPlayerName:@""]para restaurar o núcleo padrão.
UrlSource for FairPlay
Apenas o esquema FairPlay sobre o protocolo HLS é suportado.
Primeiro, consulte Live Packaging para configure a criptografia DRM. Ao reproduzir um vídeo com criptografia DRM pelo método UrlSource, além de utilizar a mesma configuração de um vídeo comum, implemente também a interface AVPDrmDelegate para obter o certificado FairPlay e a chave do vídeo.
@interface SimplePlayerViewController()<AVPDrmDelegate>
@end
- (void)viewDidLoad {
self.player = [[AliPlayer alloc] init];
self.player.playerView = self.avpPlayerView.playerView;
self.player.drmDelegate = self;
if(the current URL is for a third-party DRM video){
[self.player setPreferPlayerName:@"AppleAVPlayer"];
}
//...
}
// Implement the AVPDrmDelegate.requestCert and requestKey interfaces. Obtain the certificate and key by following the documentation from your third-party DRM provider.
// The following example shows how to obtain a certificate and key from PallyCon. For more information, see https://pallycon.com/docs/en/multidrm.
#pragma mark AVPDrmDelegate
- (NSData *)requestCert:(AliPlayer *)player {
// You can also pre-fetch and cache the certificate to reduce startup latency. If you do, return the cached certificate here.
// If the certificate data is invalid, the player reports an error. You can also check the console for more error information.
// Replace SITE_ID with your own site ID.
const char* url = "https://license.pallycon.com/ri/fpsKeyManager.do?siteId=SITE_ID";
// Request the FairPlay certificate by using an HTTP GET request as required by the DRM provider.
// Avoid blocking this thread for an extended period.
NSData* responseData = [self performAsyncHttpGet:url];
if (!responseData) {
// Handle the exception. The player will report an error.
return nil;
}
// The response data must be Base64-decoded before being returned to the player.
NSString *base64String = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
return [self decodeBase64String:base64String];
}
- (NSData *)requestKey:(AliPlayer *)player data:(NSData *)data {
// Request the key information by using an HTTP POST request as required by the DRM provider.
NSString *urlString = [NSString stringWithFormat:@"https://license-global.pallycon.com/ri/licenseManager.do"];
const char *url = [urlString UTF8String];
// Replace TOKEN_ID with your own token ID.
NSString *headerString = [NSString stringWithFormat:@"pallycon-customdata-v2: TOKEN_ID"];
const char* headers[] = {
[headerString UTF8String]
};
int headerCount = sizeof(headers) / sizeof(headers[0]);
// Avoid blocking this thread for an extended period.
NSData* responseData = [self performAsyncHttpPost:url
headers:headers
headerCount:headerCount
data:data];
if (!responseData) {
// Handle the exception. The player will report an error.
return nil;
}
// If your token's response_format is set to `original`, return the response directly. Otherwise, you must parse the response before returning it.
// For more information, see https://pallycon.com/docs/en/multidrm/license/license-token/#token-json.
// The format and structure of the response can vary significantly among providers. Check the response carefully. If the response cannot be used for decryption, the player reports an error.
return [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}
Cliente Flutter
O cliente Flutter não oferece suporte à criptografia DRM.
Procedimento
Integre o player Flutter ao seu aplicativo. As etapas e o código de exemplo são os seguintes:
-
Integre o SDK do Alibaba Cloud Player para Flutter.
-
Crie um player para reproduzir vídeos.
Siga Basic Features. Em Step 3. Create a play source, selecione um dos métodos a seguir.
Criptografia privada de vídeo da Alibaba Cloud (criptografia privada)
VidAuth
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando o método VidAuth no ApsaraVideo for VOD, se o vídeo também contiver streams não criptografados ou com transcodificação padrão, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidAuth(
vid: "The video ID",
region: "The region ID", // Required. The region where ApsaraVideo for VOD is activated. Default: cn-shanghai.
playAuth: "<yourPlayAuth>", // Required. The PlayAuth. Obtain it by calling the GetVideoPlayAuth operation for ApsaraVideo for VOD.
playConfig: value);
});
VidSts
Ao reproduzir um vídeo HLS ou MP4 com criptografia privada usando o método VidSts no ApsaraVideo for VOD, se o vídeo também contiver streams não criptografados ou com transcodificação padrão, defina o tipo de criptografia como AliyunVoDEncryption para reproduzir apenas o stream com criptografia privada.
FlutterAliplayer.setEncryptType(EncryptType.AliyunVoDEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidSts(
vid: "The video ID",
region: "The region ID",
accessKeyId: "<yourAccessKeyId>",
accessKeySecret: "<yourAccessKeySecret>",
securityToken: "<yourSecurityToken>",
playConfig: value);
});
Criptografia privada baseada em licença
UrlSource
O SDK do player Flutter oferece suporte à criptografia privada baseada em licença com UrlSource para vídeos MP4 a partir da v6.8.0 e para vídeos HLS (taxa de bits única e adaptativa) a partir da v6.17.0.
Ao reproduzir um vídeo no formato HLS ou MP4 criptografado com criptografia privada baseada em licença usando reprodução baseada em UrlSource, chame a operação Obtain audio or video playback URL para obter a URL de reprodução. É obrigatório acrescentar etavirp_nuyila=1 à URL obtida antes de passá-la ao player. (Este parâmetro é exigido apenas para arquivos MP4. Para arquivos HLS, a URL original do vídeo pode ser usada diretamente.) A configuração do SDK do player é a mesma utilizada para um vídeo padrão, sem parâmetros adicionais.
Exemplo de URL de reprodução 1: https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1
Exemplo de URL de reprodução 2: https://example.aliyundoc.com/test.mp4?auth_key=xxxxx&etavirp_nuyila=1
// Playback URL.
String playURL = "https://example.aliyundoc.com/test.mp4?etavirp_nuyila=1"
// Create a player instance.
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
fAliplayer.setUrl(playURL);
fAliplayer.prepare();
// List player.
FlutterAliListPlayer fAliListPlayer = FlutterAliPlayerFactory.createAliListPlayer();
fAliListPlayer.addUrlSource(playURL,uid);
fAliListPlayer.moveTo("uid");
// Preload.
FlutterAliPlayerMediaLoader fAliPlayerMediaLoader = FlutterAliPlayerMediaLoader();
fAliPlayerMediaLoader.load(playURL,"duration");
Criptografia padrão HLS
VidAuth
Ao reproduzir um vídeo HLS com criptografia padrão usando o método VidAuth no ApsaraVideo for VOD, se o vídeo também contiver streams com outros tipos de criptografia ou streams transcodificados sem criptografia, você pode definir o tipo de criptografia como HLSEncryption para reproduzir apenas o stream com criptografia padrão HLS. Veja o exemplo de código a seguir:
Se M3U8 Standard Encryption Rewrite estiver ativo, chame setHlsUriToken para passar o token do usuário.
FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption); // Optional. Set to HLSEncryption to return only HLS standard encrypted video streams.
FlutterAliplayer.setHlsUriToken("token"); // Optional. If you need to validate the MtsHlsUriToken, use this parameter to pass the token.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidAuth(
vid: "The video ID",
region: "The region ID", // Required. The region where ApsaraVideo for VOD is activated. Default: cn-shanghai.
playAuth: "<yourPlayAuth>", // Required. The PlayAuth. Obtain it by calling the GetVideoPlayAuth operation for ApsaraVideo for VOD.
playConfig: value);
});
VidSts
Ao reproduzir um vídeo HLS com criptografia padrão usando o método VidSts no ApsaraVideo for VOD, se o vídeo também contiver streams com outros tipos de criptografia ou streams transcodificados sem criptografia, você pode definir o tipo de criptografia como HLSEncryption para reproduzir apenas o stream com criptografia padrão HLS. Veja o exemplo de código a seguir:
Se M3U8 Standard Encryption Rewrite estiver ativo, chame setHlsUriToken para passar o token do usuário.
FlutterAliplayer.setEncryptType(EncryptType.HLSEncryption); // Optional. If you set this to AliyunVoDEncryption, only privately encrypted video streams are returned.
FlutterAliplayer.setHlsUriToken("token"); // Optional. If you need to validate the MtsHlsUriToken, use this parameter to pass the token.
FlutterAliplayer.generatePlayerConfig().then((value) {
this.fAliplayer.setVidSts(
vid: "The video ID",
region: "The region ID",
accessKeyId: "<yourAccessKeyId>",
accessKeySecret: "<yourAccessKeySecret>",
securityToken: "<yourSecurityToken>",
playConfig: value);
});
UrlSource
Ao usar o método UrlSource para reproduzir um stream ao vivo ou sob demanda com criptografia padrão HLS, a configuração do SDK do player é a mesma utilizada para um vídeo padrão.
Para obter a URL de reprodução, recomendamos chamar a operação GetPlayInfo no ApsaraVideo for VOD.
Após ativar M3U8 Standard Encryption Rewrite, é obrigatório acrescentar o parâmetro MtsHlsUriToken=<token> à URL de reprodução antes de passá-la ao player. Esse parâmetro pode ser inserido em qualquer posição na query string da URL.
Exemplo de URL de reprodução original: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8.
Exemplo de URL a ser passada ao player: https://demo.aliyundoc.com/encrypt-stream****-hd.m3u8?MtsHlsUriToken=<token>.
// Create a player instance.
FlutterAliplayer fAliplayer = FlutterAliPlayerFactory.createAliPlayer();
// The playback URL is for an HLS standard encrypted live or on-demand stream.
fAliplayer.setUrl("The playback URL");
fAliplayer.prepare();
FAQ
Problemas comuns e soluções: Video Encryption FAQ.