Skip to content

Commit 61995e2

Browse files
authored
Merge pull request #4 from devsapp/add-http-transcode
Add http transcode module
2 parents 5e53439 + 30a3473 commit 61995e2

11 files changed

Lines changed: 570 additions & 1 deletion

File tree

‎http-transcode/.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
tmp
2+
.s

‎http-transcode/hook/index.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
async function preInit(inputObj) {
2+
3+
}
4+
5+
async function postInit(inputObj) {
6+
console.log(`\n _______ _______ __ __ _______ _______ _______
7+
| || || |_| || || || |
8+
| ___|| ___|| || _ || ___|| ___|
9+
| |___ | |___ | || |_| || |___ | | __
10+
| ___|| ___|| || ___|| ___|| || |
11+
| | | | | ||_|| || | | |___ | |_| |
12+
|___| |___| |_| |_||___| |_______||_______|
13+
`)
14+
console.log(`\n Welcome to the ffmpeg-app application
15+
This application requires to open these services:
16+
FC : https://fc.console.aliyun.com/
17+
This application can help you quickly deploy the ffmpeg-app project.
18+
The application uses FC component:https://github.com/devsapp/fc
19+
The application homepage: https://github.com/devsapp/start-ffmpeg\n`)
20+
}
21+
22+
module.exports = {
23+
postInit,
24+
preInit
25+
}

‎http-transcode/publish.yaml‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
Type: Application
2+
Name: http-video-transcode
3+
Provider:
4+
- 阿里云
5+
Version: 0.0.1
6+
Description: 快速部署音视频转码的应用到阿里云函数计算
7+
HomePage: https://github.com/devsapp/start-ffmpeg
8+
Tags:
9+
- 部署函数
10+
- 音视频转码
11+
Category: 基础云服务
12+
Service:
13+
函数计算:
14+
Authorities:
15+
- AliyunFCFullAccess
16+
Parameters:
17+
type: object
18+
additionalProperties: false # 不允许增加其他属性
19+
required: # 必填项
20+
- region
21+
- serviceName
22+
- roleArn
23+
- timeZone
24+
properties:
25+
region:
26+
title: 地域
27+
type: string
28+
default: cn-hangzhou
29+
description: 创建应用所在的地区
30+
enum:
31+
- cn-beijing
32+
- cn-hangzhou
33+
- cn-shanghai
34+
- cn-qingdao
35+
- cn-zhangjiakou
36+
- cn-huhehaote
37+
- cn-shenzhen
38+
- cn-chengdu
39+
- cn-hongkong
40+
- ap-southeast-1
41+
- ap-southeast-2
42+
- ap-southeast-3
43+
- ap-southeast-5
44+
- ap-northeast-1
45+
- eu-central-1
46+
- eu-west-1
47+
- us-west-1
48+
- us-east-1
49+
- ap-south-1
50+
serviceName:
51+
title: 服务名
52+
type: string
53+
default: VideoTranscoder
54+
description: 应用所属的函数计算服务
55+
required: true
56+
roleArn:
57+
title: RAM角色ARN
58+
type: string
59+
default: ''
60+
pattern: '^acs:ram::[0-9]*:role/.*$'
61+
description: 应用所属的函数计算服务配置的 role, 请提前创建好对应的 role, 授信函数计算服务, 并配置好 AliyunOSSFullAccess 和 AliyunFCFullAccess policy
62+
required: true
63+
timeZone:
64+
title: 时区
65+
type: string
66+
default: Asia/Shanghai
67+
description: 创建的应用函数执行时候所在实例的时区, 详情参考 https://docs.oracle.com/middleware/12211/wcs/tag-ref/MISC/TimeZones.html
68+
required: true

‎http-transcode/readme.md‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# 阿里云 FFmpeg 视频转码案例
2+
3+
> 快速部署和体验 Serverless 架构下的 FFmpeg 视频转码案例
4+
5+
- [阿里云 FFmpeg 视频转码案例](#阿里云-ffmpeg-视频转码案例)
6+
- [体验前准备](#体验前准备)
7+
- [代码](#代码)
8+
- [快速部署和体验](#快速部署和体验)
9+
- [在线快速体验](#在线快速体验)
10+
- [在本地部署体验](#在本地部署体验)
11+
- [调用函数](#调用函数)
12+
- [应用详情](#应用详情)
13+
- [拥有函数计算和Serverless工作流两个产品的优势](#拥有函数计算和serverless工作流两个产品的优势)
14+
- [相较于通用的转码处理服务的优点](#相较于通用的转码处理服务的优点)
15+
- [相比于其他自建服务的优点](#相比于其他自建服务的优点)
16+
17+
## 体验前准备
18+
19+
该应用案例,需要您开通[阿里云函数计算](https://fcnext.console.aliyun.com/) 产品;并建议您当前的账号有权限存在`FCDefaultRole`。
20+
21+
## 代码
22+
23+
- [:octocat: 源代码](https://github.com/devsapp/start-ffmpeg/tree/master/http-transcode/src)
24+
25+
## 快速部署和体验
26+
### 在线快速体验
27+
28+
- 通过阿里云 **Serverless 应用中心**: 可以点击 [【🚀 部署】](https://fcnext.console.aliyun.com/applications/create?template=http-video-transcode) ,按照引导填入参数,快速进行部署和体验。
29+
30+
### 在本地部署体验
31+
32+
1. 下载安装 Serverless Devs:`npm install @serverless-devs/s`
33+
> 详细文档可以参考 [Serverless Devs 安装文档](https://github.com/Serverless-Devs/Serverless-Devs/blob/master/docs/zh/install.md)
34+
2. 配置密钥信息:`s config add`
35+
> 详细文档可以参考 [阿里云密钥配置文档](https://github.com/devsapp/fc/blob/main/docs/zh/config.md)
36+
3. 初始化项目:`s init http-video-transcode -d http-video-transcode`
37+
4. 进入项目并部署:`cd http-video-transcode && s deploy`
38+
39+
### 调用函数
40+
41+
1. 发起 5 次异步任务函数调用
42+
43+
```bash
44+
$ curl -v -H "X-Fc-Invocation-Type: Async" -H "Content-Type: application/json" -d '{"bucket":"my-bucket", "object":"480P.mp4", "output_dir":"a", "dst_format":"mov"}' -X POST https://http-***.cn-shenzhen.fcapp.run/
45+
46+
$ curl -v -H "X-Fc-Invocation-Type: Async" -H "Content-Type: application/json" -d '{"bucket":"my-bucket", "object":"480P.mp4", "output_dir":"a", "dst_format":"mov"}' -X POST https://http-***.cn-shenzhen.fcapp.run/
47+
48+
$ curl -v -H "X-Fc-Invocation-Type: Async" -H "Content-Type: application/json" -d '{"bucket":"my-bucket", "object":"480P.mp4", "output_dir":"a", "dst_format":"flv"}' -X POST https://http-***.cn-shenzhen.fcapp.run/
49+
50+
$ curl -v -H "X-Fc-Invocation-Type: Async" -H "Content-Type: application/json" -d '{"bucket":"my-bucket", "object":"480P.mp4", "output_dir":"a", "dst_format":"avi"}' -X POST https://http-***.cn-shenzhen.fcapp.run/
51+
52+
$ curl -v -H "X-Fc-Invocation-Type: Async" -H "Content-Type: application/json" -d '{"bucket":"my-bucket", "object":"480P.mp4", "output_dir":"a", "dst_format":"m3u8"}' -X POST https://http-***.cn-shenzhen.fcapp.run/
53+
54+
```
55+
56+
2. 登录[FC 控制台](https://fcnext.console.aliyun.com/)
57+
58+
![](https://img.alicdn.com/imgextra/i4/O1CN01jN5xQl1oUvle8aXFq_!!6000000005229-2-tps-1795-871.png)
59+
60+
可以清晰看出每一次转码任务的执行情况:
61+
62+
- A 视频是什么时候开始转码的, 什么时候转码结束
63+
- B 视频转码任务不太符合预期, 我中途可以点击停止调用
64+
- 通过调用状态过滤和时间窗口过滤,我可以知道现在有多少个任务正在执行, 历史完成情况是怎么样的
65+
- 可以追溯每次转码任务执行日志和触发payload
66+
- 当您的转码函数有异常时候, 会触发 dest-fail 函数的执行,您在这个函数可以添加您自定义的逻辑, 比如报警
67+
- ...
68+
69+
转码完毕后, 您也可以登录 OSS 控制台到指定的输出目录查看转码后的视频。
70+
71+
> 在本地使用该项目时,不仅可以部署,还可以进行更多的操作,例如查看日志,查看指标,进行多种模式的调试等,这些操作详情可以参考[函数计算组件命令文档](https://github.com/devsapp/fc#%E6%96%87%E6%A1%A3%E7%9B%B8%E5%85%B3) ;
72+
73+
## 应用详情
74+
75+
本项目是基于函数计算打造一个 **Serverless架构的弹性高可用音视频处理系统**, 并且拥有以下优势:
76+
77+
### 拥有函数计算和Serverless工作流两个产品的优势
78+
79+
* 无需采购和管理服务器等基础设施,只需专注视频处理业务逻辑的开发,大幅缩短项目交付时间、减少人力成本。
80+
81+
* 提供日志查询、性能监控、报警等功能,可以快速排查故障。
82+
83+
* 以事件驱动的方式触发响应请求。
84+
85+
* 免运维,毫秒级别弹性伸缩,快速实现底层扩容以应对峰值压力,性能优异。
86+
87+
* 成本极具竞争力。
88+
89+
90+
<!-- -->
91+
### 相较于通用的转码处理服务的优点
92+
93+
* 超强自定义,对用户透明,基于FFmpeg或其他音视频处理工具命令快速开发相应的音视频处理逻辑。
94+
95+
* 一键迁移原基于FFmpeg自建的音视频处理服务。
96+
97+
* 弹性更强,可以保证有充足的计算资源为转码服务,例如每周五定期产生几百个4 GB以上的1080P大视频,但是需要几小时内全部处理。
98+
99+
* 音频格式的转换或各种采样率自定义、音频降噪等功能。例如专业音频处理工具AACgain和MP3Gain。
100+
101+
* 可以和Serverless工作流完成更加复杂、自定义的任务编排。例如视频转码完成后,记录转码详情到数据库,同时自动将热度很高的视频预热到CDN上,从而缓解源站压力。
102+
103+
* 更多方式的事件驱动,例如可以选择OSS自动触发,也可以根据业务选择MNS消息触发。
104+
105+
* 在大部分场景下具有很强的成本竞争力。
106+
107+
108+
<!-- -->
109+
### 相比于其他自建服务的优点
110+
111+
* 毫秒级弹性伸缩,弹性能力超强,支持大规模资源调用,可弹性支持几万核的计算力,例如1万节课半个小时内完成转码。
112+
113+
* 只需要专注业务逻辑代码即可,原生自带事件驱动模式,简化开发编程模型,同时可以达到消息,即音视频任务,处理的优先级,可大大提高开发运维效率。
114+
115+
* 函数计算采用3AZ部署,安全性高,计算资源也是多AZ获取,能保证每位使用者需要的算力峰值。
116+
117+
* 开箱即用的监控系统,可以多维度监控函数的执行情况,根据监控快速定位问题,同时给您提供分析能力。
118+
119+
* 在大部分场景下具有很强的成本竞争力,因为函数计算是真正的按量付费,计费粒度在百毫秒,可以理解为CPU的利用率为100%。
120+
121+
122+
通过 Serverless Devs 开发者工具,您只需要几步,就可以体验 Serverless 架构,带来的降本提效的技术红利。
123+
124+
-----
125+
126+
> - Serverless Devs 项目:https://www.github.com/serverless-devs/serverless-devs
127+
> - Serverless Devs 文档:https://www.github.com/serverless-devs/docs
128+
> - Serverless Devs 钉钉交流群:33947367
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# -*- coding: utf-8 -*-
2+
import logging
3+
4+
5+
def handler(event, context):
6+
logger = logging.getLogger()
7+
logger.info('destnation fail: {}'.format(event))
8+
# do your things
9+
# ...
10+
return {}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# -*- coding: utf-8 -*-
2+
import logging
3+
4+
5+
def handler(event, context):
6+
logger = logging.getLogger()
7+
logger.info('destnation success: {}'.format(event))
8+
# do your things
9+
# ...
10+
return {}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# -*- coding: utf-8 -*-
2+
import logging
3+
import oss2
4+
import os
5+
import json
6+
import subprocess
7+
import shutil
8+
9+
logging.getLogger("oss2.api").setLevel(logging.ERROR)
10+
logging.getLogger("oss2.auth").setLevel(logging.ERROR)
11+
LOGGER = logging.getLogger()
12+
13+
14+
def get_fileNameExt(filename):
15+
(_, tempfilename) = os.path.split(filename)
16+
(shortname, extension) = os.path.splitext(tempfilename)
17+
return shortname, extension
18+
19+
20+
def handler(environ, start_response):
21+
context = environ['fc.context']
22+
# get request_body
23+
try:
24+
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
25+
except (ValueError):
26+
request_body_size = 0
27+
event = environ['wsgi.input'].read(request_body_size)
28+
29+
evt = json.loads(event)
30+
oss_bucket_name = evt["bucket"]
31+
object_key = evt["object"]
32+
output_dir = evt["output_dir"]
33+
dst_format = evt['dst_format']
34+
shortname, _ = get_fileNameExt(object_key)
35+
creds = context.credentials
36+
auth = oss2.StsAuth(creds.accessKeyId,
37+
creds.accessKeySecret, creds.securityToken)
38+
oss_client = oss2.Bucket(auth, 'oss-%s-internal.aliyuncs.com' %
39+
context.region, oss_bucket_name)
40+
41+
# simplifiedmeta = oss_client.get_object_meta(object_key)
42+
# size = float(simplifiedmeta.headers['Content-Length'])
43+
# M_size = round(size / 1024.0 / 1024.0, 2)
44+
45+
input_path = oss_client.sign_url('GET', object_key, 6 * 3600)
46+
# m3u8 特殊处理
47+
rid = context.request_id
48+
if dst_format == "m3u8":
49+
return handle_m3u8(rid, oss_client, input_path, shortname, output_dir)
50+
else:
51+
return handle_common(rid, oss_client, input_path, shortname, output_dir, dst_format)
52+
53+
54+
def handle_m3u8(request_id, oss_client, input_path, shortname, output_dir):
55+
ts_dir = '/tmp/ts'
56+
if os.path.exists(ts_dir):
57+
shutil.rmtree(ts_dir)
58+
os.mkdir(ts_dir)
59+
transcoded_filepath = os.path.join('/tmp', shortname + '.ts')
60+
split_transcoded_filepath = os.path.join(
61+
ts_dir, shortname + '_%03d.ts')
62+
cmd1 = ['ffmpeg', '-y', '-i', input_path, '-c:v',
63+
'libx264', transcoded_filepath]
64+
cmd2 = ['ffmpeg', '-y', '-i', transcoded_filepath, '-f', 'segment',
65+
'-segment_list', os.path.join(ts_dir, 'playlist.m3u8'), '-segment_time', '10', split_transcoded_filepath]
66+
try:
67+
subprocess.run(
68+
cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
69+
70+
subprocess.run(
71+
cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
72+
73+
for filename in os.listdir(ts_dir):
74+
filepath = os.path.join(ts_dir, filename)
75+
filekey = os.path.join(output_dir, shortname, filename)
76+
oss_client.put_object_from_file(filekey, filepath)
77+
os.remove(filepath)
78+
print("Uploaded {} to {}".format(filepath, filekey))
79+
80+
except subprocess.CalledProcessError as exc:
81+
# if transcode fail,trigger invoke dest-fail function
82+
raise Exception(request_id +
83+
" transcode failure, detail: " + str(exc))
84+
85+
finally:
86+
if os.path.exists(ts_dir):
87+
shutil.rmtree(ts_dir)
88+
89+
# remove ts 文件
90+
if os.path.exists(transcoded_filepath):
91+
os.remove(transcoded_filepath)
92+
return {}
93+
94+
95+
def handle_common(request_id, oss_client, input_path, shortname, output_dir, dst_format):
96+
transcoded_filepath = os.path.join('/tmp', shortname + '.' + dst_format)
97+
if os.path.exists(transcoded_filepath):
98+
os.remove(transcoded_filepath)
99+
cmd = ["ffmpeg", "-y", "-i", input_path, transcoded_filepath]
100+
try:
101+
subprocess.run(
102+
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
103+
104+
oss_client.put_object_from_file(
105+
os.path.join(output_dir, shortname + '.' + dst_format), transcoded_filepath)
106+
except subprocess.CalledProcessError as exc:
107+
# if transcode fail,trigger invoke dest-fail function
108+
raise Exception(request_id +
109+
" transcode failure, detail: " + str(exc))
110+
finally:
111+
if os.path.exists(transcoded_filepath):
112+
os.remove(transcoded_filepath)
113+
return {}

0 commit comments

Comments
 (0)