]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/core-utils/videos/bitrate.ts
18c6e2f6cef4ef6c45de5b97cf3b0399959317ad
[github/Chocobozzz/PeerTube.git] / shared / core-utils / videos / bitrate.ts
1 import { VideoResolution } from "@shared/models"
2
3 type BitPerPixel = { [ id in VideoResolution ]: number }
4
5 // https://bitmovin.com/video-bitrate-streaming-hls-dash/
6
7 const averageBitPerPixel: BitPerPixel = {
8 [VideoResolution.H_NOVIDEO]: 0,
9 [VideoResolution.H_144P]: 0.19,
10 [VideoResolution.H_240P]: 0.17,
11 [VideoResolution.H_360P]: 0.15,
12 [VideoResolution.H_480P]: 0.12,
13 [VideoResolution.H_720P]: 0.11,
14 [VideoResolution.H_1080P]: 0.10,
15 [VideoResolution.H_1440P]: 0.09,
16 [VideoResolution.H_4K]: 0.08
17 }
18
19 const maxBitPerPixel: BitPerPixel = {
20 [VideoResolution.H_NOVIDEO]: 0,
21 [VideoResolution.H_144P]: 0.32,
22 [VideoResolution.H_240P]: 0.29,
23 [VideoResolution.H_360P]: 0.26,
24 [VideoResolution.H_480P]: 0.22,
25 [VideoResolution.H_720P]: 0.19,
26 [VideoResolution.H_1080P]: 0.17,
27 [VideoResolution.H_1440P]: 0.16,
28 [VideoResolution.H_4K]: 0.14
29 }
30
31 function getAverageBitrate (options: {
32 resolution: VideoResolution
33 ratio: number
34 fps: number
35 }) {
36 const targetBitrate = calculateBitrate({ ...options, bitPerPixel: averageBitPerPixel })
37 if (!targetBitrate) return 192 * 1000
38
39 return targetBitrate
40 }
41
42 function getMaxBitrate (options: {
43 resolution: VideoResolution
44 ratio: number
45 fps: number
46 }) {
47 const targetBitrate = calculateBitrate({ ...options, bitPerPixel: maxBitPerPixel })
48 if (!targetBitrate) return 256 * 1000
49
50 return targetBitrate
51 }
52
53 // ---------------------------------------------------------------------------
54
55 export {
56 getAverageBitrate,
57 getMaxBitrate
58 }
59
60 // ---------------------------------------------------------------------------
61
62 function calculateBitrate (options: {
63 bitPerPixel: BitPerPixel
64 resolution: VideoResolution
65 ratio: number
66 fps: number
67 }) {
68 const { bitPerPixel, resolution, ratio, fps } = options
69
70 const resolutionsOrder = [
71 VideoResolution.H_4K,
72 VideoResolution.H_1440P,
73 VideoResolution.H_1080P,
74 VideoResolution.H_720P,
75 VideoResolution.H_480P,
76 VideoResolution.H_360P,
77 VideoResolution.H_240P,
78 VideoResolution.H_144P,
79 VideoResolution.H_NOVIDEO
80 ]
81
82 for (const toTestResolution of resolutionsOrder) {
83 if (toTestResolution <= resolution) {
84 return Math.floor(resolution * resolution * ratio * fps * bitPerPixel[toTestResolution])
85 }
86 }
87
88 throw new Error('Unknown resolution ' + resolution)
89 }