Debian Codegraph @

Xh264/index.js

raw
1 const debug = require('debug')('h264-profile-level-id');
2
3 /* eslint-disable no-console */
4 debug.log = console.info.bind(console);
5 /* eslint-enable no-console */
6
7 const ProfileConstrainedBaseline = 1;
8 const ProfileBaseline = 2;
9 const ProfileMain = 3;
10 const ProfileConstrainedHigh = 4;
11 const ProfileHigh = 5;
12
13 exports.ProfileConstrainedBaseline = ProfileConstrainedBaseline;
14 exports.ProfileBaseline = ProfileBaseline;
15 exports.ProfileMain = ProfileMain;
16 exports.ProfileConstrainedHigh = ProfileConstrainedHigh;
17 exports.ProfileHigh = ProfileHigh;
18
19 // All values are equal to ten times the level number, except level 1b which is
20 // special.
21 const Level1_b = 0;
22 const Level1 = 10;
23 const Level1_1 = 11;
24 const Level1_2 = 12;
25 const Level1_3 = 13;
26 const Level2 = 20;
27 const Level2_1 = 21;
28 const Level2_2 = 22;
29 const Level3 = 30;
30 const Level3_1 = 31;
31 const Level3_2 = 32;
32 const Level4 = 40;
33 const Level4_1 = 41;
34 const Level4_2 = 42;
35 const Level5 = 50;
36 const Level5_1 = 51;
37 const Level5_2 = 52;
38
39 exports.Level1_b = Level1_b;
40 exports.Level1 = Level1;
41 exports.Level1_1 = Level1_1;
42 exports.Level1_2 = Level1_2;
43 exports.Level1_3 = Level1_3;
44 exports.Level2 = Level2;
45 exports.Level2_1 = Level2_1;
46 exports.Level2_2 = Level2_2;
47 exports.Level3 = Level3;
48 exports.Level3_1 = Level3_1;
49 exports.Level3_2 = Level3_2;
50 exports.Level4 = Level4;
51 exports.Level4_1 = Level4_1;
52 exports.Level4_2 = Level4_2;
53 exports.Level5 = Level5;
54 exports.Level5_1 = Level5_1;
55 exports.Level5_2 = Level5_2;
56
57 class ProfileLevelId
58 {
59 constructor(profile, level)
60 {
61 this.profile = profile;
62 this.level = level;
63 }
64 }
65
66 exports.ProfileLevelId = ProfileLevelId;
67
68 // Default ProfileLevelId.
69 //
70 // TODO: The default should really be profile Baseline and level 1 according to
71 // the spec: https://tools.ietf.org/html/rfc6184#section-8.1. In order to not
72 // break backwards compatibility with older versions of WebRTC where external
73 // codecs don't have any parameters, use profile ConstrainedBaseline level 3_1
74 // instead. This workaround will only be done in an interim period to allow
75 // external clients to update their code.
76 //
77 // http://crbug/webrtc/6337.
78 const DefaultProfileLevelId =
79 new ProfileLevelId(ProfileConstrainedBaseline, Level3_1);
80
81 // For level_idc=11 and profile_idc=0x42, 0x4D, or 0x58, the constraint set3
82 // flag specifies if level 1b or level 1.1 is used.
83 const ConstraintSet3Flag = 0x10;
84
85 // Class for matching bit patterns such as "x1xx0000" where 'x' is allowed to be
86 // either 0 or 1.
87 class BitPattern
88 {
89 constructor(str)
90 {
91 this._mask = ~byteMaskString('x', str);
92 this._maskedValue = byteMaskString('1', str);
93 }
94
95 isMatch(value)
96 {
97 return this._maskedValue === (value & this._mask);
98 }
99 }
100
101 // Class for converting between profile_idc/profile_iop to Profile.
102 class ProfilePattern
103 {
104 constructor(profile_idc, profile_iop, profile)
105 {
106 this.profile_idc = profile_idc;
107 this.profile_iop = profile_iop;
108 this.profile = profile;
109 }
110 }
111
112 // This is from https://tools.ietf.org/html/rfc6184#section-8.1.
113 const ProfilePatterns =
114 [
115 new ProfilePattern(0x42, new BitPattern('x1xx0000'), ProfileConstrainedBaseline),
116 new ProfilePattern(0x4D, new BitPattern('1xxx0000'), ProfileConstrainedBaseline),
117 new ProfilePattern(0x58, new BitPattern('11xx0000'), ProfileConstrainedBaseline),
118 new ProfilePattern(0x42, new BitPattern('x0xx0000'), ProfileBaseline),
119 new ProfilePattern(0x58, new BitPattern('10xx0000'), ProfileBaseline),
120 new ProfilePattern(0x4D, new BitPattern('0x0x0000'), ProfileMain),
121 new ProfilePattern(0x64, new BitPattern('00000000'), ProfileHigh),
122 new ProfilePattern(0x64, new BitPattern('00001100'), ProfileConstrainedHigh)
123 ];
124
125 /**
126 * Parse profile level id that is represented as a string of 3 hex bytes.
127 * Nothing will be returned if the string is not a recognized H264 profile
128 * level id.
129 *
130 * @param {String} str - profile-level-id value as a string of 3 hex bytes.
131 *
132 * @returns {ProfileLevelId}
133 */
134 exports.parseProfileLevelId = function(str)
135 {
136 // The string should consist of 3 bytes in hexadecimal format.
137 if (typeof str !== 'string' || str.length !== 6)
138 return null;
139
140 const profile_level_id_numeric = parseInt(str, 16);
141
142 if (profile_level_id_numeric === 0)
143 return null;
144
145 // Separate into three bytes.
146 const level_idc = profile_level_id_numeric & 0xFF;
147 const profile_iop = (profile_level_id_numeric >> 8) & 0xFF;
148 const profile_idc = (profile_level_id_numeric >> 16) & 0xFF;
149
150 // Parse level based on level_idc and constraint set 3 flag.
151 let level;
152
153 switch (level_idc)
154 {
155 case Level1_1:
156 {
157 level = (profile_iop & ConstraintSet3Flag) !== 0 ? Level1_b : Level1_1;
158 break;
159 }
160 case Level1:
161 case Level1_2:
162 case Level1_3:
163 case Level2:
164 case Level2_1:
165 case Level2_2:
166 case Level3:
167 case Level3_1:
168 case Level3_2:
169 case Level4:
170 case Level4_1:
171 case Level4_2:
172 case Level5:
173 case Level5_1:
174 case Level5_2:
175 {
176 level = level_idc;
177 break;
178 }
179 // Unrecognized level_idc.
180 default:
181 {
182 debug('parseProfileLevelId() | unrecognized level_idc:%s', level_idc);
183
184 return null;
185 }
186 }
187
188 // Parse profile_idc/profile_iop into a Profile enum.
189 for (const pattern of ProfilePatterns)
190 {
191 if (
192 profile_idc === pattern.profile_idc &&
193 pattern.profile_iop.isMatch(profile_iop)
194 )
195 {
196 return new ProfileLevelId(pattern.profile, level);
197 }
198 }
199
200 debug('parseProfileLevelId() | unrecognized profile_idc/profile_iop combination');
201
202 return null;
203 };
204
205 /**
206 * Returns canonical string representation as three hex bytes of the profile
207 * level id, or returns nothing for invalid profile level ids.
208 *
209 * @param {ProfileLevelId} profile_level_id
210 *
211 * @returns {String}
212 */
213 exports.profileLevelIdToString = function(profile_level_id)
214 {
215 // Handle special case level == 1b.
216 if (profile_level_id.level == Level1_b)
217 {
218 switch (profile_level_id.profile)
219 {
220 case ProfileConstrainedBaseline:
221 {
222 return '42f00b';
223 }
224 case ProfileBaseline:
225 {
226 return '42100b';
227 }
228 case ProfileMain:
229 {
230 return '4d100b';
231 }
232 // Level 1_b is not allowed for other profiles.
233 default:
234 {
235 debug(
236 'profileLevelIdToString() | Level 1_b not is allowed for profile:%s',
237 profile_level_id.profile);
238
239 return null;
240 }
241 }
242 }
243
244 let profile_idc_iop_string;
245
246 switch (profile_level_id.profile)
247 {
248 case ProfileConstrainedBaseline:
249 {
250 profile_idc_iop_string = '42e0';
251 break;
252 }
253 case ProfileBaseline:
254 {
255 profile_idc_iop_string = '4200';
256 break;
257 }
258 case ProfileMain:
259 {
260 profile_idc_iop_string = '4d00';
261 break;
262 }
263 case ProfileConstrainedHigh:
264 {
265 profile_idc_iop_string = '640c';
266 break;
267 }
268 case ProfileHigh:
269 {
270 profile_idc_iop_string = '6400';
271 break;
272 }
273 default:
274 {
275 debug(
276 'profileLevelIdToString() | unrecognized profile:%s',
277 profile_level_id.profile);
278
279 return null;
280 }
281 }
282
283 let levelStr = (profile_level_id.level).toString(16);
284
285 if (levelStr.length === 1)
286 levelStr = `0${levelStr}`;
287
288 return `${profile_idc_iop_string}${levelStr}`;
289 };
290
291 /**
292 * Parse profile level id that is represented as a string of 3 hex bytes
293 * contained in an SDP key-value map. A default profile level id will be
294 * returned if the profile-level-id key is missing. Nothing will be returned if
295 * the key is present but the string is invalid.
296 *
297 * @param {Object} [params={}] - Codec parameters object.
298 *
299 * @returns {ProfileLevelId}
300 */
301 exports.parseSdpProfileLevelId = function(params = {})
302 {
303 const profile_level_id = params['profile-level-id'];
304
305 return !profile_level_id
306 ? DefaultProfileLevelId
307 : exports.parseProfileLevelId(profile_level_id);
308 };
309
310 /**
311 * Returns true if the parameters have the same H264 profile, i.e. the same
312 * H264 profile (Baseline, High, etc).
313 *
314 * @param {Object} [params1={}] - Codec parameters object.
315 * @param {Object} [params2={}] - Codec parameters object.
316 *
317 * @returns {Boolean}
318 */
319 exports.isSameProfile = function(params1 = {}, params2 = {})
320 {
321 const profile_level_id_1 = exports.parseSdpProfileLevelId(params1);
322 const profile_level_id_2 = exports.parseSdpProfileLevelId(params2);
323
324 // Compare H264 profiles, but not levels.
325 return Boolean(
326 profile_level_id_1 &&
327 profile_level_id_2 &&
328 profile_level_id_1.profile === profile_level_id_2.profile
329 );
330 };
331
332 /**
333 * Generate codec parameters that will be used as answer in an SDP negotiation
334 * based on local supported parameters and remote offered parameters. Both
335 * local_supported_params and remote_offered_params represent sendrecv media
336 * descriptions, i.e they are a mix of both encode and decode capabilities. In
337 * theory, when the profile in local_supported_params represent a strict superset
338 * of the profile in remote_offered_params, we could limit the profile in the
339 * answer to the profile in remote_offered_params.
340 *
341 * However, to simplify the code, each supported H264 profile should be listed
342 * explicitly in the list of local supported codecs, even if they are redundant.
343 * Then each local codec in the list should be tested one at a time against the
344 * remote codec, and only when the profiles are equal should this function be
345 * called. Therefore, this function does not need to handle profile intersection,
346 * and the profile of local_supported_params and remote_offered_params must be
347 * equal before calling this function. The parameters that are used when
348 * negotiating are the level part of profile-level-id and level-asymmetry-allowed.
349 *
350 * @param {Object} [local_supported_params={}]
351 * @param {Object} [remote_offered_params={}]
352 *
353 * @returns {String} Canonical string representation as three hex bytes of the
354 * profile level id, or null if no one of the params have profile-level-id.
355 *
356 * @throws {TypeError} If Profile mismatch or invalid params.
357 */
358 exports.generateProfileLevelIdForAnswer = function(
359 local_supported_params = {},
360 remote_offered_params = {}
361 )
362 {
363 // If both local and remote params do not contain profile-level-id, they are
364 // both using the default profile. In this case, don't return anything.
365 if (
366 !local_supported_params['profile-level-id'] &&
367 !remote_offered_params['profile-level-id']
368 )
369 {
370 debug(
371 'generateProfileLevelIdForAnswer() | no profile-level-id in local and remote params');
372
373 return null;
374 }
375
376 // Parse profile-level-ids.
377 const local_profile_level_id =
378 exports.parseSdpProfileLevelId(local_supported_params);
379 const remote_profile_level_id =
380 exports.parseSdpProfileLevelId(remote_offered_params);
381
382 // The local and remote codec must have valid and equal H264 Profiles.
383 if (!local_profile_level_id)
384 throw new TypeError('invalid local_profile_level_id');
385
386 if (!remote_profile_level_id)
387 throw new TypeError('invalid remote_profile_level_id');
388
389 if (local_profile_level_id.profile !== remote_profile_level_id.profile)
390 throw new TypeError('H264 Profile mismatch');
391
392 // Parse level information.
393 const level_asymmetry_allowed = (
394 isLevelAsymmetryAllowed(local_supported_params) &&
395 isLevelAsymmetryAllowed(remote_offered_params)
396 );
397
398 const local_level = local_profile_level_id.level;
399 const remote_level = remote_profile_level_id.level;
400 const min_level = minLevel(local_level, remote_level);
401
402 // Determine answer level. When level asymmetry is not allowed, level upgrade
403 // is not allowed, i.e., the level in the answer must be equal to or lower
404 // than the level in the offer.
405 const answer_level = level_asymmetry_allowed ? local_level : min_level;
406
407 debug(
408 'generateProfileLevelIdForAnswer() | result: [profile:%s, level:%s]',
409 local_profile_level_id.profile, answer_level);
410
411 // Return the resulting profile-level-id for the answer parameters.
412 return exports.profileLevelIdToString(
413 new ProfileLevelId(local_profile_level_id.profile, answer_level));
414 };
415
416 // Convert a string of 8 characters into a byte where the positions containing
417 // character c will have their bit set. For example, c = 'x', str = "x1xx0000"
418 // will return 0b10110000.
419 function byteMaskString(c, str)
420 {
421 return (
422 ((str[0] === c) << 7) | ((str[1] === c) << 6) | ((str[2] === c) << 5) |
423 ((str[3] === c) << 4) | ((str[4] === c) << 3) | ((str[5] === c) << 2) |
424 ((str[6] === c) << 1) | ((str[7] === c) << 0)
425 );
426 }
427
428 // Compare H264 levels and handle the level 1b case.
429 function isLessLevel(a, b)
430 {
431 if (a === Level1_b)
432 return b !== Level1 && b !== Level1_b;
433
434 if (b === Level1_b)
435 return a !== Level1;
436
437 return a < b;
438 }
439
440 function minLevel(a, b)
441 {
442 return isLessLevel(a, b) ? a : b;
443 }
444
445 function isLevelAsymmetryAllowed(params = {})
446 {
447 const level_asymmetry_allowed = params['level-asymmetry-allowed'];
448
449 return (
450 level_asymmetry_allowed === 1 ||
451 level_asymmetry_allowed === '1'
452 );
453 }