Build an elastic and highly available audio and video processing system based on a serverless architecture

更新时间:
复制 MD 格式

Transcoding is a compute-intensive task in audio and video systems. You can use Function Compute and CloudFlow to build an elastic and highly available serverless audio and video processing system. This topic compares the serverless system with traditional solutions based on engineering efficiency, operations and maintenance (O&M), performance, and cost. It also provides instructions on how to build the serverless system.

Background information

You can use dedicated cloud services for audio and video transcoding. However, you might choose to build your own transcoding service in the following scenarios.

  • Elastic scaling requirements

    • You need a more elastic video processing service.

      For example, you have deployed a video processing service based on FFmpeg on virtual machines or a container platform but want to make the service more elastic and highly available.

  • Engineering efficiency requirements

    • You need to process multiple video files in parallel.

    • You need to quickly process multiple large videos in batches.

      For example, hundreds of large videos that are over 4 GB in 1080p resolution are generated every Friday and must be processed within a few hours.

  • Custom processing requirements

    • You need to handle advanced custom processing requirements.

      For example, after a video is transcoded, you need to record the transcoding details in a database. Or, you need to automatically prefetch popular videos to a Content Delivery Network (CDN) to reduce pressure on the origin server.

    • You need to convert audio formats, customize sample rates, or perform audio denoising.

    • You need to directly read and process source files.

      For example, if your source video files are stored on Apsara File Storage NAS or Elastic Compute Service (ECS) disks, you can build a service to read and process the files directly. You do not need to migrate them to Object Storage Service (OSS).

    • You need to convert videos to other formats and then add new features.

      For example, you can transcode a video, add a watermark, and generate a GIF for the video's cover. Then, you can add new features, such as adjusting transcoding parameters or releasing new features without affecting the online service.

  • Cost requirements

    • You need to perform simple transcoding or lightweight tasks.

      For example, obtaining a GIF of the first few frames of a video in OSS or obtaining the duration of an audio or video file. In these cases, building your own service is more cost-effective.

There are two ways to build your own transcoding service: the traditional self-built solution and the serverless solution. This topic describes the differences between these two solutions and provides the procedure for implementing the serverless solution.

Solutions

Traditional self-built solution

As computer and network technologies develop, the products of cloud computing vendors mature. To build an audio and video processing system, you can purchase ECS servers in the cloud to deploy services. You can use technologies such as OSS and CDN to store audio and video files and accelerate playback.

image

Serverless solution

Simple video processing system

If you only need to perform simple processing on videos, you can use the solution architecture that is shown in the following figure.

image

When a user uploads a video to OSS, an OSS trigger automatically invokes a function. The function calls FFmpeg to transcode the video and saves the transcoded video to OSS.

For a demo and the procedure for the simple video processing system, see Simple video processing system.

Video processing workflow system

To accelerate the transcoding of large videos or perform complex combined operations, you can use CloudFlow to orchestrate functions and build a powerful video processing system. The solution architecture is shown in the following figure.

image

When a user uploads an MP4 video to OSS, an OSS trigger automatically invokes a function. The function then calls CloudFlow to transcode the video into one or more formats. This solution meets the following requirements:

  • A video file can be transcoded into various formats simultaneously. You can also perform other custom processing, such as adding watermarks or updating information in a database after processing.

  • When multiple files are uploaded to OSS at the same time, Function Compute automatically scales to process the files in parallel. It also transcodes the files into multiple formats in parallel.

  • Using NAS and video segmentation, you can solve the problem of transcoding very large videos. For each video, you first segment it, then transcode the segments in parallel, and finally merge them. Setting a reasonable segment duration can significantly increase the transcoding speed for large videos.

    Note

    Video segmentation means splitting a video stream into a series of segment files at specified time intervals and generating a manifest to record information about the segment files.

For a demo and the procedure for the video processing workflow system, see Video processing workflow system.

Advantages of the serverless solution

Improved engineering efficiency

Comparison item

Serverless solution

Traditional self-built solution

Infrastructure

None

Purchase and management required.

Development efficiency

Focus only on developing business logic. Use Serverless Devs to orchestrate and deploy resources.

Besides developing business logic, you must also build an identical online runtime environment. This includes tasks such as installing software, configuring services, and applying security updates.

Parallel and distributed video processing

Use CloudFlow for resource orchestration to process multiple videos in parallel and process a single large video in a distributed manner. The cloud platform handles stability and monitoring.

Requires strong development skills and a comprehensive monitoring system to ensure stability.

Learning curve

You only need to know how to write function code in the corresponding language and be familiar with FFmpeg.

Besides programming skills and familiarity with FFmpeg, you may also need to use Kubernetes (K8s) and ECS. This requires understanding more products, terms, and parameters.

Time to market

Estimated at 3 person-days (2 for development and debugging, 1 for stress testing and observation).

A significant amount of time and labor is spent outside of business logic development. A conservative estimate is about 30 person-days, including hardware procurement, software and environment configuration, system development, testing, monitoring and alerting, and phased releases.

Elastic scaling and no O&M

Item

Serverless solution

Traditional self-built solution

Elasticity and high availability

The Function Compute system provides millisecond-level elastic scaling. It can quickly scale out underlying resources to handle peak pressure. It is fully managed and delivers excellent transcoding performance.

You need to build your own Server Load Balancer (SLB). The speed of elastic scaling, scale-out, and scale-in is slower than Function Compute.

Monitoring, alerting, and queries

Provides more fine-grained monitoring of CloudFlow workflow executions and function executions. You can also query the latency and logs for each function execution. The alerting and monitoring mechanism is more comprehensive.

Provides metrics at the elastic scaling or container level.

Transcoding performance advantage

Assume that a video is an 89-second MOV file. A standard cloud service takes 188 seconds to transcode the MOV file to MP4. Let's call this reference time T. The performance acceleration percentage is calculated using the following formula: Performance acceleration percentage = T ÷ Function Compute transcoding time.

Video segment duration (s)

Function Compute transcoding time (s)

Performance acceleration percentage (%)

45

160

117.5

25

100

188

15

70

268.6

10

45

417.8

5

35

537.1

Note

The performance acceleration percentages in the table above apply only to CPU instances.

Low cost

In some scenarios, Function Compute is more cost-effective for video processing. This solution has a strong cost advantage, even when compared with the unit price of other cloud vendors' video transcoding services.

The following tables show the costs of converting between MP4 and FLV, two of the most common formats for video-on-demand. The function memory is set to 3 GB. The costs are based on experimental data.

The cost reduction percentage is calculated using the following formula: Cost reduction percentage = (Another cloud's video processing fee - Function Compute transcoding fee) ÷ Another cloud's video processing fee.

Table 1. MP4 to FLV

Resolution

Bitrate

Frame rate

Function Compute transcoding time

Function Compute transcoding fee

Another cloud's video processing fee

Cost reduction percentage

Standard Definition (SD) 640×480

889 KB/s

24

11.2s

0.003732288

0.032

88.3%

High Definition (HD) 1280×720

1963 KB/s

24

20.5s

0.00683142

0.065

89.5%

Ultra High Definition (UHD) 1920×1080

3689 KB/s

24

40s

0.0133296

0.126

89.4%

4K 3840×2160

11185 KB/s

24

142s

0.04732008

0.556

91.5%

Table 2. FLV to MP4

Resolution

Bitrate

Frame rate

Function Compute transcoding time

Function Compute transcoding fee

Fees for third-party cloud video processing

Cost reduction percentage

Standard Definition (SD) 640×480

712 KB/s

24

34.5s

0.01149678

0.032

64.1%

High Definition (HD) 1280×720

1806 KB/s

24

100.3s

0.033424

0.065

48.6%

Ultra High Definition (UHD) 1920×1080

3911 KB/s

24

226.4s

0.0754455

0.126

40.1%

4K 3840×2160

15109 KB/s

24

912s

0.30391488

0.556

45.3%

Note

The other cloud's video processing service uses standard transcoding and bills by the minute. If the transcoding duration is less than one minute, it is billed as one minute. Here, the billing is based on 2 minutes. Even if it were calculated based on 1.5 minutes, the cost reduction percentage would fluctuate within 10%.

The tables show that the solution based on Function Compute and CloudFlow is highly cost-competitive for both compute-intensive conversions (FLV to MP4) and less compute-intensive conversions (MP4 to FLV). Based on practical experience, the cost reduction is often more significant than what is listed in the tables for the following reasons:

  • The bitrate of the test videos is high. In many real-world scenarios, most transcoding tasks involve standard definition (SD) or low definition (LD) videos with lower bitrates. This reduces the amount of computation, shortening the Function Compute execution time and lowering the cost. However, the billing for general-purpose cloud transcoding services remains the same.

  • For many video resolutions, billing by general-purpose cloud transcoding services can be inefficient. For example, a video with a resolution of 856×480 or 1368×768 falls into the next billing tier. A resolution of 856×480 is billed at the 1280×720 HD tier, and 1368×768 is billed at the 1920×1080 UHD tier. The unit price increases significantly, but the actual increase in computation may be less than 30%. In contrast, Function Compute offers true pay-as-you-go billing.

Deployment

This topic describes how to deploy the serverless solution for two scenarios: a simple video processing system and a video processing workflow system.

Simple video processing system

Prerequisites

Procedure

The following steps describe how to build a serverless video conversion system. When a video is uploaded to the source directory of an OSS bucket, a function is triggered. The function converts the MP4 video file to the FLV format and saves the FLV file to the dest directory in the OSS bucket.

  1. Create a function.

    Log on to the Function Compute console and select Event Function on the Create Function page. On the Create Event Function page, set the Function Name and the following options, and then click Create.

    • Elastic Configuration: Event functions support only elastic instances. You must configure the Specification Plan and Minimum Number Of Instances.

      Because video processing is a resource-intensive task, this topic sets vCPU to 4 cores, Memory to 8 GB, and Disk to 10 GB.

    • Function Code: Set the runtime to Built-in Runtime > Python > Python 3.10, the Code Upload Method to Use Sample Code, and the Execution Timeout to 7200 seconds.

    • Advanced Configuration: In the Permission category, select AliyunFcDefaultRole for Function Role.

    Use the default values for other configurations. For more information about creating a function, see Create a function.

  2. Create an OSS trigger.

    1. On the Function Details page, click the Configurations tab. In the left-side navigation pane, click Triggers. Then, click Create Trigger.

    2. In the Create Trigger panel, for Trigger Type, select Two-way Integrated Trigger > Object Storage Service (OSS). Set the remaining configuration items and click OK.

      Configuration item

      Operation

      Example

      Name

      Enter a custom name for the trigger.

      oss-trigger

      Version Or Alias

      The default value is LATEST. To create a trigger for another version or alias, you must first select the version from the Version Or Alias dropdown list on the function details page. For an introduction to versions and aliases, see Version management and Alias management.

      LATEST

      Bucket Name

      Select an existing OSS bucket.

      testbucket

      File Prefix

      Enter the prefix of the file names to match. We recommend that you configure a file prefix and suffix to avoid nested loop triggers that can cause extra fees. In addition, if different triggers for the same bucket specify the same event type, their prefixes and suffixes cannot be the same. For more information, see OSS trigger rules.

      Important

      The file prefix cannot start with /. Otherwise, the OSS trigger cannot be triggered.

      source

      File Suffix

      Enter the suffix of the file names to match. We strongly recommend that you configure a prefix and suffix to avoid nested loop triggers that can cause extra fees. In addition, if different triggers for the same bucket specify the same event type, their prefixes and suffixes cannot be the same. For more information, see OSS trigger rules.

      mp4

      Triggering Event

      Select one or more triggering events. For more information about Object Storage Service (OSS) event types, see OSS events.

      In this example, oss:ObjectCreated:PutObject is selected.

      oss:ObjectCreated:PutObject, oss:ObjectCreated:PostObject, oss:ObjectCreated:CompleteMultipartUpload

      Role Name

      Select AliyunOSSEventNotificationRole.

      Note

      If you are creating this type of trigger for the first time, click OK, and then select Authorize Now in the pop-up dialog box.

      AliyunOSSEventNotificationRole

      Important

      Note that you can configure only one OSS trigger for a single prefix in a bucket. If you configure multiple triggers, a Cannot specify overlapping prefix and suffix with same event type error occurs. To resolve this issue, use one of the following methods:

      • For Bucket Name, enter the name of another bucket.

      • Change the prefix name.

      • Delete the conflicting OSS trigger.

  3. Write the function code.

    1. On the function details page, click the Code tab and write code in the editor.

      This topic uses Python as an example. The sample code is as follows.

      # -*- coding: utf-8 -*-
      import logging
      import oss2
      import os
      import json
      import subprocess
      import shutil
      
      logging.getLogger("oss2.api").setLevel(logging.ERROR)
      logging.getLogger("oss2.auth").setLevel(logging.ERROR)
      LOGGER = logging.getLogger()
      
      
      def get_fileNameExt(filename):
          (_, tempfilename) = os.path.split(filename)
          (shortname, extension) = os.path.splitext(tempfilename)
          return shortname, extension
      
      
      def handler(event, context):
          LOGGER.info(event)
          evt = json.loads(event)
          evt = evt["events"]
          oss_bucket_name = evt[0]["oss"]["bucket"]["name"]
          object_key = evt[0]["oss"]["object"]["key"]
          
          output_dir = "dest"
          dst_format = "flv"
          shortname, _ = get_fileNameExt(object_key)
          creds = context.credentials
          auth = oss2.StsAuth(creds.accessKeyId,
                              creds.accessKeySecret, creds.securityToken)
          oss_client = oss2.Bucket(auth, 'oss-%s-internal.aliyuncs.com' %
                                   context.region, oss_bucket_name)
      
          exist = oss_client.object_exists(object_key)
          if not exist:
              raise Exception("object {} is not exist".format(object_key))
      
          input_path = oss_client.sign_url('GET', object_key, 6 * 3600)
          # Special handling for m3u8
          rid = context.request_id
          if dst_format == "m3u8":
              return handle_m3u8(rid, oss_client, input_path, shortname, output_dir)
          else:
              return handle_common(rid, oss_client, input_path, shortname, output_dir, dst_format)
      
      
      def handle_m3u8(request_id, oss_client, input_path, shortname, output_dir):
          ts_dir = '/tmp/ts'
          if os.path.exists(ts_dir):
              shutil.rmtree(ts_dir)
          os.mkdir(ts_dir)
          transcoded_filepath = os.path.join('/tmp', shortname + '.ts')
          split_transcoded_filepath = os.path.join(
              ts_dir, shortname + '_%03d.ts')
          cmd1 = ['ffmpeg', '-y', '-i', input_path, '-c:v',
                  'libx264', transcoded_filepath]
      
          cmd2 = ['ffmpeg', '-y', '-i', transcoded_filepath, '-c', 'copy', '-map',  '0',  '-f', 'segment',
                  '-segment_list', os.path.join(ts_dir, 'playlist.m3u8'), '-segment_time', '10', split_transcoded_filepath]
      
          try:
              subprocess.run(
                  cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
      
              subprocess.run(
                  cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
      
              for filename in os.listdir(ts_dir):
                  filepath = os.path.join(ts_dir, filename)
                  filekey = os.path.join(output_dir, shortname, filename)
                  oss_client.put_object_from_file(filekey, filepath)
                  os.remove(filepath)
                  print("Uploaded {} to {}".format(filepath, filekey))
      
          except subprocess.CalledProcessError as exc:
              # If transcoding fails, trigger the dest-fail function
              raise Exception(request_id + " transcode failure, detail: " + str(exc))
      
          finally:
              if os.path.exists(ts_dir):
                  shutil.rmtree(ts_dir)
      
              # Remove the .ts file
              if os.path.exists(transcoded_filepath):
                  os.remove(transcoded_filepath)
      
          return {}
      
      
      def handle_common(request_id, oss_client, input_path, shortname, output_dir, dst_format):
          transcoded_filepath = os.path.join('/tmp', shortname + '.' + dst_format)
          if os.path.exists(transcoded_filepath):
              os.remove(transcoded_filepath)
          cmd = ["ffmpeg", "-y", "-i", input_path, transcoded_filepath]
          try:
              subprocess.run(
                  cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
      
              oss_client.put_object_from_file(
                  os.path.join(output_dir, shortname + '.' + dst_format), transcoded_filepath)
          except subprocess.CalledProcessError as exc:
              # If transcoding fails, trigger the dest-fail function
              raise Exception(request_id + " transcode failure, detail: " + str(exc))
          finally:
              if os.path.exists(transcoded_filepath):
                  os.remove(transcoded_filepath)
          return {}
      
    2. Click Deploy Code.

  4. Test the function code.

    You can configure the function's entry point parameter to simulate an OSS event parameter to test the code. In a real-world scenario, the function is automatically triggered when an OSS event occurs.

    1. On the function details page, click the Code tab. Then, click the drop-down icon icon to the right of Test Function and select Configure Test Parameters from the drop-down list.

    2. In the Configure Test Parameters panel, select the Create New Test Event or Edit Existing Test Event tab, enter the Event Name and event content, and click OK.

      The event template for this topic is as follows. Replace the bucket name, ETag, and video file name with your actual values.

      {
          "events": [
              {
                  "eventName": "oss:ObjectCreated:CompleteMultipartUpload",
                  "eventSource": "acs:oss",
                  "eventTime": "2022-08-13T06:45:43.000Z",
                  "eventVersion": "1.0",
                  "oss": {
                      "bucket": {
                          "name": "testbucket"
                      },
                      "object": {
                          "eTag": "688A7BF4F233DC9C88A80BF985AB****",
                          "key": "source/a.mp4"
                      }
                  },
                  "region": "cn-hangzhou"
              }
          ]
      }
      Note

      An ETag (entity tag) is created when an object is generated to identify the content of the object. You can find the ETag by clicking Details for the target object in the OSS file list.

      image

      For more information about event parameters, see Configure function entry point parameters.

    3. Click Test Function. After the function runs successfully, you can find the converted video file at the dest/ path in the target bucket.

      image

Video processing workflow system

Prerequisites

  • Activate services and create a bucket

  • Configure Resource Access Management (RAM) roles

    • AliyunFcDefaultRole: This role is required when you create a function. The role must have the AliyunFCInvocationAccess, AliyunFnFFullAccess, and AliyunOSSFullAccess permissions to invoke functions, manage workflows, and manage OSS.

    • AliyunOSSEventNotificationRole: OSS uses this role by default to send event notifications.

    • fnf-execution-default-role: This role is required to create and manage workflows. The role must have the AliyunFCInvocationAccess and AliyunFnFFullAccess permissions.

      In the Trust Policy for the role, grant the workflow service the AssumeRole permission, as shown below.

      {
        "Statement": [
          {
            "Action": "sts:AssumeRole",
            "Effect": "Allow",
            "Principal": {
              "Service": [
                "fnf.aliyuncs.com"
              ]
            }
          }
        ],
        "Version": "1"
      }
  • Install and configure Serverless Devs

    Quick Start

Procedure

This solution uses CloudFlow to orchestrate functions to build the video processing system. It involves configuring and writing code for multiple functions and a workflow. This topic uses Serverless Devs to deploy the system.

  1. Run the following command to initialize the application.

    s init multimedia-process-flow-v3 -d multimedia-process-flow-v3

    During the process, you need to configure the following information. Configure the items based on your requirements.

    Configuration item

    Example

    Region

    cn-hangzhou

    Workflow name

    multimedia-process-flow-demo

    Workflow RAM role ARN

    acs:ram::10343546****:role/fnf-execution-default-role

    Function Compute Service RAM role ARN

    acs:ram::10343546****:role/aliyunfcdefaultrole

    OSS bucket name

    testBucket

    Prefix

    source

    Directory to save transcoded videos

    dest

    OSS trigger RAM role ARN

    acs:ram::10343546****:role/aliyunosseventnotificationrole

    Segment duration for video segmentation

    30

    Formats for transcoded videos

    mp4, flv, avi

    please select credential alias

    default

    Important

    Serverless Devs creates an OSS trigger. Note that you can configure only one OSS trigger for a single prefix in a bucket. If you configure multiple triggers, a Cannot specify overlapping prefix and suffix with same event type error occurs during project deployment.

    To resolve this issue, use one of the following methods:

    • Set the OSS Bucket Name to the name of a different bucket.

    • Change the prefix name.

    • Delete the conflicting OSS trigger.

  2. Run the following commands to go to the project directory and deploy the project.

    cd multimedia-process-flow-v3 && s deploy -y

    The following output indicates a successful deployment:

    Result for [deploy] of [multimedia-process-flow-v3]
    ====================
    split: 
      region:         cn-hangzhou
      description:    
      functionArn:    acs:fc:cn-hangzhou:1327************:functions/multimedia-process-flow-****_split
      functionName:   multimedia-process-flow-****_split
      handler:        index.handler
      internetAccess: true
      memorySize:     3072
      nasConfig: 
        groupId:     0
        mountPoints: 
          - 
            enableTLS:  false
            mountDir:   /mnt/multimedia-process-flow-****_split
            serverAddr: 0d7c******-*****.cn-hangzhou.nas.aliyuncs.com:/multimedia-process-flow-****_split
        userId:      0
      role:           acs:ram::1327************:role/aliyunfcdefaultrole
      runtime:        python3
      timeout:        600
      vpcConfig: 
        securityGroupId: sg-********************
        vSwitchIds: 
          - vsw-bp1dc5zwx9egt16ondd2f
        vpcId:           vpc-********************
      __component:    fc3
    transcode: 
      region:         cn-hangzhou
      description:    
      functionArn:    acs:fc:cn-hangzhou:1327************:functions/multimedia-process-flow-****_transcode
      functionName:   multimedia-process-flow-****_transcode
      handler:        index.handler
      internetAccess: true
      memorySize:     3072
      nasConfig: 
        groupId:     0
        mountPoints: 
          - 
            enableTLS:  false
            mountDir:   /mnt/multimedia-process-flow-****_split
            serverAddr: 0d7c******-*****.cn-hangzhou.nas.aliyuncs.com:/multimedia-process-flow-****_split
        userId:      0
      role:           acs:ram::1327************:role/aliyunfcdefaultrole
      runtime:        python3
      timeout:        600
      vpcConfig: 
        securityGroupId: sg-********************
        vSwitchIds: 
          - vsw-bp1dc5zwx9egt16ondd2f
        vpcId:           vpc-********************
      __component:    fc3
    merge: 
      region:         cn-hangzhou
      description:    
      functionArn:    acs:fc:cn-hangzhou:1327************:functions/multimedia-process-flow-****_merge
      functionName:   multimedia-process-flow-****_merge
      handler:        index.handler
      internetAccess: true
      memorySize:     3072
      nasConfig: 
        groupId:     0
        mountPoints: 
          - 
            enableTLS:  false
            mountDir:   /mnt/multimedia-process-flow-****_split
            serverAddr: 0d7c******-*****.cn-hangzhou.nas.aliyuncs.com:/multimedia-process-flow-****_split
        userId:      0
      role:           acs:ram::1327************:role/aliyunfcdefaultrole
      runtime:        python3
      timeout:        600
      vpcConfig: 
        securityGroupId: sg-********************
        vSwitchIds: 
          - vsw-bp1dc5zwx9egt16ondd2f
        vpcId:           vpc-********************
      __component:    fc3
    after-process: 
      region:         cn-hangzhou
      cpu:            0.35
      description:    
      diskSize:       512
      functionArn:    acs:fc:cn-hangzhou:1327************:functions/multimedia-process-flow-****_after-process
      functionName:   multimedia-process-flow-****_after-process
      handler:        index.handler
      internetAccess: true
      memorySize:     512
      nasConfig: 
        groupId:     0
        mountPoints: 
          - 
            enableTLS:  false
            mountDir:   /mnt/multimedia-process-flow-****_split
            serverAddr: 0d7c******-*****.cn-hangzhou.nas.aliyuncs.com:/multimedia-process-flow-****_split
        userId:      0
      role:           acs:ram::1327************:role/aliyunfcdefaultrole
      runtime:        python3
      timeout:        120
      vpcConfig: 
        securityGroupId: sg-********************
        vSwitchIds: 
          - vsw-bp1dc5zwx9egt16ondd2f
        vpcId:           vpc-********************
      __component:    fc3
    oss-trigger-workflow: 
      region:               cn-hangzhou
      description:          
      environmentVariables: 
        DST_FORMATS:  mp4, flv, avi
        FLOW_NAME:    multimedia-process-flow-****
        OUTPUT_DST:   dest
        SEG_INTERVAL: 30
      functionArn:          acs:fc:cn-hangzhou:1327************:functions/multimedia-process-flow-****_oss-trigger-workflow
      functionName:         multimedia-process-flow-****_oss-trigger-workflow
      handler:              index.handler
      internetAccess:       true
      memorySize:           128
      role:                 acs:ram::1327************:role/aliyunfcdefaultrole
      runtime:              python3
      timeout:              120
      triggers: 
        - 
          description:    
          invocationRole: acs:ram::1327************:role/aliyunosseventnotificationrole
          qualifier:      LATEST
          sourceArn:      acs:oss:cn-hangzhou:1327************:csy-test-bucket-hz-20241009
          triggerConfig: 
            events: 
              - oss:ObjectCreated:PutObject
              - oss:ObjectCreated:PostObject
              - oss:ObjectCreated:CompleteMultipartUpload
            filter: 
              key: 
                prefix: source
                suffix: 
          triggerName:    multimedia-process-flow-****
          triggerType:    oss
      __component:          fc3
    multimedia-process-v3-workflow: 
      region:           cn-hangzhou
      createdTime:      2024-10-09T11:17:50.379Z
      definition:       ...
      description:      Serverless workflow video process
      executionMode:    Standard
      id:               4b8cd4cb-158c-4e57-8b0e-************
      lastModifiedTime: 2024-10-09T11:17:50.379Z
      name:             multimedia-process-flow-****
      requestId:        a4cfa607-b980-9534-c89e-************
      roleArn:          acs:ram::1327************:role/fnf-execution-default-role
      type:             FDL
      __component:      flow
  3. Test the project.

    1. Log on to the OSS console. Then, go to the source directory of the destination bucket and upload an MP4 video file.

    2. Log on to the CloudFlow console. On the Workflow List page, click the target workflow. On the Execution History tab, click the name of the target execution to view its flow and status.

      image

    3. When the job status is Execution Succeeded, you can view the transcoded video file in the dest/ folder of the target Bucket.

References

FAQ

  • If you have already deployed a video processing service based on FFmpeg on a virtual machine or container platform, how can you increase its elasticity and availability?

    You can easily switch your FFmpeg-based service to Function Compute. FFmpeg commands can be migrated directly to Function Compute with low overhead. This lets your service inherit the elastic and high-availability features of Function Compute.

  • How do I concurrently process many videos?

    For the deployment solution, see Video processing workflow system. When multiple files are uploaded to OSS simultaneously, Function Compute automatically scales to process the files in parallel. For more information, see Stress testing the video processing workflow system.

  • How can I quickly batch process hundreds of large videos, such as 1080P videos over 4 GB, within a few hours?

    You can control the shard size to allocate sufficient computing resources for transcoding each large video. This significantly increases the transcoding speed. For the deployment solution, see Stress testing the video processing workflow system.

  • How can I perform advanced custom tasks, such as recording transcoding details to a database or prefetching popular videos to CDN after transcoding is complete?

    See Video processing workflow system for the deployment solution. You can add custom operations during processing or add extra steps to the workflow, such as adding post-processing steps or a pre-processing step at the beginning.

  • My video processing workflow combines multiple operations, such as transcoding, adding watermarks, and generating GIFs. How can I add new features, such as adjusting transcoding parameters, without affecting my online service?

    See Video processing workflow system for the deployment solution. CloudFlow only orchestrates function calls. Therefore, you can simply update the relevant processing function. Functions also support versions and aliases, which give you better control over grayscale releases. For more information, see Version control.

  • What is the most cost-effective way to handle simple, lightweight tasks, such as generating a GIF from the first few frames of a video in OSS or getting the duration of a media file?

    Function Compute can handle these custom tasks. You can simply execute a few FFmpeg commands in your code to complete the task. For a sample project, see fc-oss-ffmpeg.

  • My source video files are on NAS or ECS disks. How can I process them directly without migrating them to OSS?

    Function Compute can mount a NAS file system to process files directly. For more information, see Configure a NAS file system.