You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1142 lines
38KB

  1. /*
  2. * Copyright (c) 2014 Tim Walker <tdskywalker@gmail.com>
  3. *
  4. * This file is part of Libav.
  5. *
  6. * Libav is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * Libav is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with Libav; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "libavcodec/avcodec.h"
  21. #include "libavcodec/get_bits.h"
  22. #include "libavcodec/golomb_legacy.h"
  23. #include "libavcodec/hevc.h"
  24. #include "libavutil/intreadwrite.h"
  25. #include "avc.h"
  26. #include "avio.h"
  27. #include "hevc.h"
  28. #define MAX_SPATIAL_SEGMENTATION 4096 // max. value of u(12) field
  29. typedef struct HVCCNALUnitArray {
  30. uint8_t array_completeness;
  31. uint8_t NAL_unit_type;
  32. uint16_t numNalus;
  33. uint16_t *nalUnitLength;
  34. uint8_t **nalUnit;
  35. } HVCCNALUnitArray;
  36. typedef struct HEVCDecoderConfigurationRecord {
  37. uint8_t configurationVersion;
  38. uint8_t general_profile_space;
  39. uint8_t general_tier_flag;
  40. uint8_t general_profile_idc;
  41. uint32_t general_profile_compatibility_flags;
  42. uint64_t general_constraint_indicator_flags;
  43. uint8_t general_level_idc;
  44. uint16_t min_spatial_segmentation_idc;
  45. uint8_t parallelismType;
  46. uint8_t chromaFormat;
  47. uint8_t bitDepthLumaMinus8;
  48. uint8_t bitDepthChromaMinus8;
  49. uint16_t avgFrameRate;
  50. uint8_t constantFrameRate;
  51. uint8_t numTemporalLayers;
  52. uint8_t temporalIdNested;
  53. uint8_t lengthSizeMinusOne;
  54. uint8_t numOfArrays;
  55. HVCCNALUnitArray *array;
  56. } HEVCDecoderConfigurationRecord;
  57. typedef struct HVCCProfileTierLevel {
  58. uint8_t profile_space;
  59. uint8_t tier_flag;
  60. uint8_t profile_idc;
  61. uint32_t profile_compatibility_flags;
  62. uint64_t constraint_indicator_flags;
  63. uint8_t level_idc;
  64. } HVCCProfileTierLevel;
  65. static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc,
  66. HVCCProfileTierLevel *ptl)
  67. {
  68. /*
  69. * The value of general_profile_space in all the parameter sets must be
  70. * identical.
  71. */
  72. hvcc->general_profile_space = ptl->profile_space;
  73. /*
  74. * The level indication general_level_idc must indicate a level of
  75. * capability equal to or greater than the highest level indicated for the
  76. * highest tier in all the parameter sets.
  77. */
  78. if (hvcc->general_tier_flag < ptl->tier_flag)
  79. hvcc->general_level_idc = ptl->level_idc;
  80. else
  81. hvcc->general_level_idc = FFMAX(hvcc->general_level_idc, ptl->level_idc);
  82. /*
  83. * The tier indication general_tier_flag must indicate a tier equal to or
  84. * greater than the highest tier indicated in all the parameter sets.
  85. */
  86. hvcc->general_tier_flag = FFMAX(hvcc->general_tier_flag, ptl->tier_flag);
  87. /*
  88. * The profile indication general_profile_idc must indicate a profile to
  89. * which the stream associated with this configuration record conforms.
  90. *
  91. * If the sequence parameter sets are marked with different profiles, then
  92. * the stream may need examination to determine which profile, if any, the
  93. * entire stream conforms to. If the entire stream is not examined, or the
  94. * examination reveals that there is no profile to which the entire stream
  95. * conforms, then the entire stream must be split into two or more
  96. * sub-streams with separate configuration records in which these rules can
  97. * be met.
  98. *
  99. * Note: set the profile to the highest value for the sake of simplicity.
  100. */
  101. hvcc->general_profile_idc = FFMAX(hvcc->general_profile_idc, ptl->profile_idc);
  102. /*
  103. * Each bit in general_profile_compatibility_flags may only be set if all
  104. * the parameter sets set that bit.
  105. */
  106. hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags;
  107. /*
  108. * Each bit in general_constraint_indicator_flags may only be set if all
  109. * the parameter sets set that bit.
  110. */
  111. hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags;
  112. }
  113. static void hvcc_parse_ptl(GetBitContext *gb,
  114. HEVCDecoderConfigurationRecord *hvcc,
  115. unsigned int max_sub_layers_minus1)
  116. {
  117. unsigned int i;
  118. HVCCProfileTierLevel general_ptl;
  119. uint8_t sub_layer_profile_present_flag[HEVC_MAX_SUB_LAYERS];
  120. uint8_t sub_layer_level_present_flag[HEVC_MAX_SUB_LAYERS];
  121. general_ptl.profile_space = get_bits(gb, 2);
  122. general_ptl.tier_flag = get_bits1(gb);
  123. general_ptl.profile_idc = get_bits(gb, 5);
  124. general_ptl.profile_compatibility_flags = get_bits_long(gb, 32);
  125. general_ptl.constraint_indicator_flags = get_bits64(gb, 48);
  126. general_ptl.level_idc = get_bits(gb, 8);
  127. hvcc_update_ptl(hvcc, &general_ptl);
  128. for (i = 0; i < max_sub_layers_minus1; i++) {
  129. sub_layer_profile_present_flag[i] = get_bits1(gb);
  130. sub_layer_level_present_flag[i] = get_bits1(gb);
  131. }
  132. if (max_sub_layers_minus1 > 0)
  133. for (i = max_sub_layers_minus1; i < 8; i++)
  134. skip_bits(gb, 2); // reserved_zero_2bits[i]
  135. for (i = 0; i < max_sub_layers_minus1; i++) {
  136. if (sub_layer_profile_present_flag[i]) {
  137. /*
  138. * sub_layer_profile_space[i] u(2)
  139. * sub_layer_tier_flag[i] u(1)
  140. * sub_layer_profile_idc[i] u(5)
  141. * sub_layer_profile_compatibility_flag[i][0..31] u(32)
  142. * sub_layer_progressive_source_flag[i] u(1)
  143. * sub_layer_interlaced_source_flag[i] u(1)
  144. * sub_layer_non_packed_constraint_flag[i] u(1)
  145. * sub_layer_frame_only_constraint_flag[i] u(1)
  146. * sub_layer_reserved_zero_44bits[i] u(44)
  147. */
  148. skip_bits_long(gb, 32);
  149. skip_bits_long(gb, 32);
  150. skip_bits (gb, 24);
  151. }
  152. if (sub_layer_level_present_flag[i])
  153. skip_bits(gb, 8);
  154. }
  155. }
  156. static void skip_sub_layer_hrd_parameters(GetBitContext *gb,
  157. unsigned int cpb_cnt_minus1,
  158. uint8_t sub_pic_hrd_params_present_flag)
  159. {
  160. unsigned int i;
  161. for (i = 0; i <= cpb_cnt_minus1; i++) {
  162. get_ue_golomb_long(gb); // bit_rate_value_minus1
  163. get_ue_golomb_long(gb); // cpb_size_value_minus1
  164. if (sub_pic_hrd_params_present_flag) {
  165. get_ue_golomb_long(gb); // cpb_size_du_value_minus1
  166. get_ue_golomb_long(gb); // bit_rate_du_value_minus1
  167. }
  168. skip_bits1(gb); // cbr_flag
  169. }
  170. }
  171. static void skip_hrd_parameters(GetBitContext *gb, uint8_t cprms_present_flag,
  172. unsigned int max_sub_layers_minus1)
  173. {
  174. unsigned int i;
  175. uint8_t sub_pic_hrd_params_present_flag = 0;
  176. uint8_t nal_hrd_parameters_present_flag = 0;
  177. uint8_t vcl_hrd_parameters_present_flag = 0;
  178. if (cprms_present_flag) {
  179. nal_hrd_parameters_present_flag = get_bits1(gb);
  180. vcl_hrd_parameters_present_flag = get_bits1(gb);
  181. if (nal_hrd_parameters_present_flag ||
  182. vcl_hrd_parameters_present_flag) {
  183. sub_pic_hrd_params_present_flag = get_bits1(gb);
  184. if (sub_pic_hrd_params_present_flag)
  185. /*
  186. * tick_divisor_minus2 u(8)
  187. * du_cpb_removal_delay_increment_length_minus1 u(5)
  188. * sub_pic_cpb_params_in_pic_timing_sei_flag u(1)
  189. * dpb_output_delay_du_length_minus1 u(5)
  190. */
  191. skip_bits(gb, 19);
  192. /*
  193. * bit_rate_scale u(4)
  194. * cpb_size_scale u(4)
  195. */
  196. skip_bits(gb, 8);
  197. if (sub_pic_hrd_params_present_flag)
  198. skip_bits(gb, 4); // cpb_size_du_scale
  199. /*
  200. * initial_cpb_removal_delay_length_minus1 u(5)
  201. * au_cpb_removal_delay_length_minus1 u(5)
  202. * dpb_output_delay_length_minus1 u(5)
  203. */
  204. skip_bits(gb, 15);
  205. }
  206. }
  207. for (i = 0; i <= max_sub_layers_minus1; i++) {
  208. unsigned int cpb_cnt_minus1 = 0;
  209. uint8_t low_delay_hrd_flag = 0;
  210. uint8_t fixed_pic_rate_within_cvs_flag = 0;
  211. uint8_t fixed_pic_rate_general_flag = get_bits1(gb);
  212. if (!fixed_pic_rate_general_flag)
  213. fixed_pic_rate_within_cvs_flag = get_bits1(gb);
  214. if (fixed_pic_rate_within_cvs_flag)
  215. get_ue_golomb_long(gb); // elemental_duration_in_tc_minus1
  216. else
  217. low_delay_hrd_flag = get_bits1(gb);
  218. if (!low_delay_hrd_flag)
  219. cpb_cnt_minus1 = get_ue_golomb_long(gb);
  220. if (nal_hrd_parameters_present_flag)
  221. skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
  222. sub_pic_hrd_params_present_flag);
  223. if (vcl_hrd_parameters_present_flag)
  224. skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
  225. sub_pic_hrd_params_present_flag);
  226. }
  227. }
  228. static void skip_timing_info(GetBitContext *gb)
  229. {
  230. skip_bits_long(gb, 32); // num_units_in_tick
  231. skip_bits_long(gb, 32); // time_scale
  232. if (get_bits1(gb)) // poc_proportional_to_timing_flag
  233. get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
  234. }
  235. static void hvcc_parse_vui(GetBitContext *gb,
  236. HEVCDecoderConfigurationRecord *hvcc,
  237. unsigned int max_sub_layers_minus1)
  238. {
  239. unsigned int min_spatial_segmentation_idc;
  240. if (get_bits1(gb)) // aspect_ratio_info_present_flag
  241. if (get_bits(gb, 8) == 255) // aspect_ratio_idc
  242. skip_bits_long(gb, 32); // sar_width u(16), sar_height u(16)
  243. if (get_bits1(gb)) // overscan_info_present_flag
  244. skip_bits1(gb); // overscan_appropriate_flag
  245. if (get_bits1(gb)) { // video_signal_type_present_flag
  246. skip_bits(gb, 4); // video_format u(3), video_full_range_flag u(1)
  247. if (get_bits1(gb)) // colour_description_present_flag
  248. /*
  249. * colour_primaries u(8)
  250. * transfer_characteristics u(8)
  251. * matrix_coeffs u(8)
  252. */
  253. skip_bits(gb, 24);
  254. }
  255. if (get_bits1(gb)) { // chroma_loc_info_present_flag
  256. get_ue_golomb_long(gb); // chroma_sample_loc_type_top_field
  257. get_ue_golomb_long(gb); // chroma_sample_loc_type_bottom_field
  258. }
  259. /*
  260. * neutral_chroma_indication_flag u(1)
  261. * field_seq_flag u(1)
  262. * frame_field_info_present_flag u(1)
  263. */
  264. skip_bits(gb, 3);
  265. if (get_bits1(gb)) { // default_display_window_flag
  266. get_ue_golomb_long(gb); // def_disp_win_left_offset
  267. get_ue_golomb_long(gb); // def_disp_win_right_offset
  268. get_ue_golomb_long(gb); // def_disp_win_top_offset
  269. get_ue_golomb_long(gb); // def_disp_win_bottom_offset
  270. }
  271. if (get_bits1(gb)) { // vui_timing_info_present_flag
  272. skip_timing_info(gb);
  273. if (get_bits1(gb)) // vui_hrd_parameters_present_flag
  274. skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
  275. }
  276. if (get_bits1(gb)) { // bitstream_restriction_flag
  277. /*
  278. * tiles_fixed_structure_flag u(1)
  279. * motion_vectors_over_pic_boundaries_flag u(1)
  280. * restricted_ref_pic_lists_flag u(1)
  281. */
  282. skip_bits(gb, 3);
  283. min_spatial_segmentation_idc = get_ue_golomb_long(gb);
  284. /*
  285. * unsigned int(12) min_spatial_segmentation_idc;
  286. *
  287. * The min_spatial_segmentation_idc indication must indicate a level of
  288. * spatial segmentation equal to or less than the lowest level of
  289. * spatial segmentation indicated in all the parameter sets.
  290. */
  291. hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
  292. min_spatial_segmentation_idc);
  293. get_ue_golomb_long(gb); // max_bytes_per_pic_denom
  294. get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
  295. get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
  296. get_ue_golomb_long(gb); // log2_max_mv_length_vertical
  297. }
  298. }
  299. static void skip_sub_layer_ordering_info(GetBitContext *gb)
  300. {
  301. get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
  302. get_ue_golomb_long(gb); // max_num_reorder_pics
  303. get_ue_golomb_long(gb); // max_latency_increase_plus1
  304. }
  305. static int hvcc_parse_vps(GetBitContext *gb,
  306. HEVCDecoderConfigurationRecord *hvcc)
  307. {
  308. unsigned int vps_max_sub_layers_minus1;
  309. /*
  310. * vps_video_parameter_set_id u(4)
  311. * vps_reserved_three_2bits u(2)
  312. * vps_max_layers_minus1 u(6)
  313. */
  314. skip_bits(gb, 12);
  315. vps_max_sub_layers_minus1 = get_bits(gb, 3);
  316. /*
  317. * numTemporalLayers greater than 1 indicates that the stream to which this
  318. * configuration record applies is temporally scalable and the contained
  319. * number of temporal layers (also referred to as temporal sub-layer or
  320. * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
  321. * indicates that the stream is not temporally scalable. Value 0 indicates
  322. * that it is unknown whether the stream is temporally scalable.
  323. */
  324. hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
  325. vps_max_sub_layers_minus1 + 1);
  326. /*
  327. * vps_temporal_id_nesting_flag u(1)
  328. * vps_reserved_0xffff_16bits u(16)
  329. */
  330. skip_bits(gb, 17);
  331. hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
  332. /* nothing useful for hvcC past this point */
  333. return 0;
  334. }
  335. static void skip_scaling_list_data(GetBitContext *gb)
  336. {
  337. int i, j, k, num_coeffs;
  338. for (i = 0; i < 4; i++)
  339. for (j = 0; j < (i == 3 ? 2 : 6); j++)
  340. if (!get_bits1(gb)) // scaling_list_pred_mode_flag[i][j]
  341. get_ue_golomb_long(gb); // scaling_list_pred_matrix_id_delta[i][j]
  342. else {
  343. num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
  344. if (i > 1)
  345. get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
  346. for (k = 0; k < num_coeffs; k++)
  347. get_se_golomb_long(gb); // scaling_list_delta_coef
  348. }
  349. }
  350. static int parse_rps(GetBitContext *gb, unsigned int rps_idx,
  351. unsigned int num_rps,
  352. unsigned int num_delta_pocs[HEVC_MAX_SHORT_TERM_RPS_COUNT])
  353. {
  354. unsigned int i;
  355. if (rps_idx && get_bits1(gb)) { // inter_ref_pic_set_prediction_flag
  356. /* this should only happen for slice headers, and this isn't one */
  357. if (rps_idx >= num_rps)
  358. return AVERROR_INVALIDDATA;
  359. skip_bits1 (gb); // delta_rps_sign
  360. get_ue_golomb_long(gb); // abs_delta_rps_minus1
  361. num_delta_pocs[rps_idx] = 0;
  362. /*
  363. * From libavcodec/hevc_ps.c:
  364. *
  365. * if (is_slice_header) {
  366. * //foo
  367. * } else
  368. * rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
  369. *
  370. * where:
  371. * rps: &sps->st_rps[rps_idx]
  372. * sps->st_rps: &sps->st_rps[0]
  373. * is_slice_header: rps_idx == num_rps
  374. *
  375. * thus:
  376. * if (num_rps != rps_idx)
  377. * rps_ridx = &sps->st_rps[rps_idx - 1];
  378. *
  379. * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
  380. */
  381. for (i = 0; i < num_delta_pocs[rps_idx - 1]; i++) {
  382. uint8_t use_delta_flag = 0;
  383. uint8_t used_by_curr_pic_flag = get_bits1(gb);
  384. if (!used_by_curr_pic_flag)
  385. use_delta_flag = get_bits1(gb);
  386. if (used_by_curr_pic_flag || use_delta_flag)
  387. num_delta_pocs[rps_idx]++;
  388. }
  389. } else {
  390. unsigned int num_negative_pics = get_ue_golomb_long(gb);
  391. unsigned int num_positive_pics = get_ue_golomb_long(gb);
  392. num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
  393. for (i = 0; i < num_negative_pics; i++) {
  394. get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
  395. skip_bits1 (gb); // used_by_curr_pic_s0_flag[rps_idx]
  396. }
  397. for (i = 0; i < num_positive_pics; i++) {
  398. get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
  399. skip_bits1 (gb); // used_by_curr_pic_s1_flag[rps_idx]
  400. }
  401. }
  402. return 0;
  403. }
  404. static int hvcc_parse_sps(GetBitContext *gb,
  405. HEVCDecoderConfigurationRecord *hvcc)
  406. {
  407. unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4;
  408. unsigned int num_short_term_ref_pic_sets, num_delta_pocs[HEVC_MAX_SHORT_TERM_RPS_COUNT];
  409. skip_bits(gb, 4); // sps_video_parameter_set_id
  410. sps_max_sub_layers_minus1 = get_bits (gb, 3);
  411. /*
  412. * numTemporalLayers greater than 1 indicates that the stream to which this
  413. * configuration record applies is temporally scalable and the contained
  414. * number of temporal layers (also referred to as temporal sub-layer or
  415. * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
  416. * indicates that the stream is not temporally scalable. Value 0 indicates
  417. * that it is unknown whether the stream is temporally scalable.
  418. */
  419. hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
  420. sps_max_sub_layers_minus1 + 1);
  421. hvcc->temporalIdNested = get_bits1(gb);
  422. hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
  423. get_ue_golomb_long(gb); // sps_seq_parameter_set_id
  424. hvcc->chromaFormat = get_ue_golomb_long(gb);
  425. if (hvcc->chromaFormat == 3)
  426. skip_bits1(gb); // separate_colour_plane_flag
  427. get_ue_golomb_long(gb); // pic_width_in_luma_samples
  428. get_ue_golomb_long(gb); // pic_height_in_luma_samples
  429. if (get_bits1(gb)) { // conformance_window_flag
  430. get_ue_golomb_long(gb); // conf_win_left_offset
  431. get_ue_golomb_long(gb); // conf_win_right_offset
  432. get_ue_golomb_long(gb); // conf_win_top_offset
  433. get_ue_golomb_long(gb); // conf_win_bottom_offset
  434. }
  435. hvcc->bitDepthLumaMinus8 = get_ue_golomb_long(gb);
  436. hvcc->bitDepthChromaMinus8 = get_ue_golomb_long(gb);
  437. log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
  438. /* sps_sub_layer_ordering_info_present_flag */
  439. i = get_bits1(gb) ? 0 : sps_max_sub_layers_minus1;
  440. for (; i <= sps_max_sub_layers_minus1; i++)
  441. skip_sub_layer_ordering_info(gb);
  442. get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
  443. get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
  444. get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
  445. get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
  446. get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
  447. get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
  448. if (get_bits1(gb) && // scaling_list_enabled_flag
  449. get_bits1(gb)) // sps_scaling_list_data_present_flag
  450. skip_scaling_list_data(gb);
  451. skip_bits1(gb); // amp_enabled_flag
  452. skip_bits1(gb); // sample_adaptive_offset_enabled_flag
  453. if (get_bits1(gb)) { // pcm_enabled_flag
  454. skip_bits (gb, 4); // pcm_sample_bit_depth_luma_minus1
  455. skip_bits (gb, 4); // pcm_sample_bit_depth_chroma_minus1
  456. get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3
  457. get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size
  458. skip_bits1 (gb); // pcm_loop_filter_disabled_flag
  459. }
  460. num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
  461. if (num_short_term_ref_pic_sets > HEVC_MAX_SHORT_TERM_RPS_COUNT)
  462. return AVERROR_INVALIDDATA;
  463. for (i = 0; i < num_short_term_ref_pic_sets; i++) {
  464. int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
  465. if (ret < 0)
  466. return ret;
  467. }
  468. if (get_bits1(gb)) { // long_term_ref_pics_present_flag
  469. for (i = 0; i < get_ue_golomb_long(gb); i++) { // num_long_term_ref_pics_sps
  470. int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
  471. skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
  472. skip_bits1(gb); // used_by_curr_pic_lt_sps_flag[i]
  473. }
  474. }
  475. skip_bits1(gb); // sps_temporal_mvp_enabled_flag
  476. skip_bits1(gb); // strong_intra_smoothing_enabled_flag
  477. if (get_bits1(gb)) // vui_parameters_present_flag
  478. hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
  479. /* nothing useful for hvcC past this point */
  480. return 0;
  481. }
  482. static int hvcc_parse_pps(GetBitContext *gb,
  483. HEVCDecoderConfigurationRecord *hvcc)
  484. {
  485. uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
  486. get_ue_golomb_long(gb); // pps_pic_parameter_set_id
  487. get_ue_golomb_long(gb); // pps_seq_parameter_set_id
  488. /*
  489. * dependent_slice_segments_enabled_flag u(1)
  490. * output_flag_present_flag u(1)
  491. * num_extra_slice_header_bits u(3)
  492. * sign_data_hiding_enabled_flag u(1)
  493. * cabac_init_present_flag u(1)
  494. */
  495. skip_bits(gb, 7);
  496. get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
  497. get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
  498. get_se_golomb_long(gb); // init_qp_minus26
  499. /*
  500. * constrained_intra_pred_flag u(1)
  501. * transform_skip_enabled_flag u(1)
  502. */
  503. skip_bits(gb, 2);
  504. if (get_bits1(gb)) // cu_qp_delta_enabled_flag
  505. get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
  506. get_se_golomb_long(gb); // pps_cb_qp_offset
  507. get_se_golomb_long(gb); // pps_cr_qp_offset
  508. /*
  509. * weighted_pred_flag u(1)
  510. * weighted_bipred_flag u(1)
  511. * transquant_bypass_enabled_flag u(1)
  512. */
  513. skip_bits(gb, 3);
  514. tiles_enabled_flag = get_bits1(gb);
  515. entropy_coding_sync_enabled_flag = get_bits1(gb);
  516. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
  517. hvcc->parallelismType = 0; // mixed-type parallel decoding
  518. else if (entropy_coding_sync_enabled_flag)
  519. hvcc->parallelismType = 3; // wavefront-based parallel decoding
  520. else if (tiles_enabled_flag)
  521. hvcc->parallelismType = 2; // tile-based parallel decoding
  522. else
  523. hvcc->parallelismType = 1; // slice-based parallel decoding
  524. /* nothing useful for hvcC past this point */
  525. return 0;
  526. }
  527. static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
  528. uint32_t *dst_len)
  529. {
  530. uint8_t *dst;
  531. uint32_t i, len;
  532. dst = av_malloc(src_len + AV_INPUT_BUFFER_PADDING_SIZE);
  533. if (!dst)
  534. return NULL;
  535. /* NAL unit header (2 bytes) */
  536. i = len = 0;
  537. while (i < 2 && i < src_len)
  538. dst[len++] = src[i++];
  539. while (i + 2 < src_len)
  540. if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
  541. dst[len++] = src[i++];
  542. dst[len++] = src[i++];
  543. i++; // remove emulation_prevention_three_byte
  544. } else
  545. dst[len++] = src[i++];
  546. while (i < src_len)
  547. dst[len++] = src[i++];
  548. *dst_len = len;
  549. return dst;
  550. }
  551. static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
  552. {
  553. skip_bits1(gb); // forbidden_zero_bit
  554. *nal_type = get_bits(gb, 6);
  555. /*
  556. * nuh_layer_id u(6)
  557. * nuh_temporal_id_plus1 u(3)
  558. */
  559. skip_bits(gb, 9);
  560. }
  561. static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
  562. uint8_t nal_type, int ps_array_completeness,
  563. HEVCDecoderConfigurationRecord *hvcc)
  564. {
  565. int ret;
  566. uint8_t index;
  567. uint16_t numNalus;
  568. HVCCNALUnitArray *array;
  569. for (index = 0; index < hvcc->numOfArrays; index++)
  570. if (hvcc->array[index].NAL_unit_type == nal_type)
  571. break;
  572. if (index >= hvcc->numOfArrays) {
  573. uint8_t i;
  574. ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
  575. if (ret < 0)
  576. return ret;
  577. for (i = hvcc->numOfArrays; i <= index; i++)
  578. memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
  579. hvcc->numOfArrays = index + 1;
  580. }
  581. array = &hvcc->array[index];
  582. numNalus = array->numNalus;
  583. ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
  584. if (ret < 0)
  585. return ret;
  586. ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
  587. if (ret < 0)
  588. return ret;
  589. array->nalUnit [numNalus] = nal_buf;
  590. array->nalUnitLength[numNalus] = nal_size;
  591. array->NAL_unit_type = nal_type;
  592. array->numNalus++;
  593. /*
  594. * When the sample entry name is ‘hvc1’, the default and mandatory value of
  595. * array_completeness is 1 for arrays of all types of parameter sets, and 0
  596. * for all other arrays. When the sample entry name is ‘hev1’, the default
  597. * value of array_completeness is 0 for all arrays.
  598. */
  599. if (nal_type == HEVC_NAL_VPS || nal_type == HEVC_NAL_SPS || nal_type == HEVC_NAL_PPS)
  600. array->array_completeness = ps_array_completeness;
  601. return 0;
  602. }
  603. static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
  604. int ps_array_completeness,
  605. HEVCDecoderConfigurationRecord *hvcc)
  606. {
  607. int ret = 0;
  608. GetBitContext gbc;
  609. uint8_t nal_type;
  610. uint8_t *rbsp_buf;
  611. uint32_t rbsp_size;
  612. rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
  613. if (!rbsp_buf) {
  614. ret = AVERROR(ENOMEM);
  615. goto end;
  616. }
  617. ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
  618. if (ret < 0)
  619. goto end;
  620. nal_unit_parse_header(&gbc, &nal_type);
  621. /*
  622. * Note: only 'declarative' SEI messages are allowed in
  623. * hvcC. Perhaps the SEI playload type should be checked
  624. * and non-declarative SEI messages discarded?
  625. */
  626. switch (nal_type) {
  627. case HEVC_NAL_VPS:
  628. case HEVC_NAL_SPS:
  629. case HEVC_NAL_PPS:
  630. case HEVC_NAL_SEI_PREFIX:
  631. case HEVC_NAL_SEI_SUFFIX:
  632. ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
  633. ps_array_completeness, hvcc);
  634. if (ret < 0)
  635. goto end;
  636. else if (nal_type == HEVC_NAL_VPS)
  637. ret = hvcc_parse_vps(&gbc, hvcc);
  638. else if (nal_type == HEVC_NAL_SPS)
  639. ret = hvcc_parse_sps(&gbc, hvcc);
  640. else if (nal_type == HEVC_NAL_PPS)
  641. ret = hvcc_parse_pps(&gbc, hvcc);
  642. if (ret < 0)
  643. goto end;
  644. break;
  645. default:
  646. ret = AVERROR_INVALIDDATA;
  647. goto end;
  648. }
  649. end:
  650. av_free(rbsp_buf);
  651. return ret;
  652. }
  653. static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
  654. {
  655. memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
  656. hvcc->configurationVersion = 1;
  657. hvcc->lengthSizeMinusOne = 3; // 4 bytes
  658. /*
  659. * The following fields have all their valid bits set by default,
  660. * the ProfileTierLevel parsing code will unset them when needed.
  661. */
  662. hvcc->general_profile_compatibility_flags = 0xffffffff;
  663. hvcc->general_constraint_indicator_flags = 0xffffffffffff;
  664. /*
  665. * Initialize this field with an invalid value which can be used to detect
  666. * whether we didn't see any VUI (in which case it should be reset to zero).
  667. */
  668. hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
  669. }
  670. static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
  671. {
  672. uint8_t i;
  673. for (i = 0; i < hvcc->numOfArrays; i++) {
  674. hvcc->array[i].numNalus = 0;
  675. av_freep(&hvcc->array[i].nalUnit);
  676. av_freep(&hvcc->array[i].nalUnitLength);
  677. }
  678. hvcc->numOfArrays = 0;
  679. av_freep(&hvcc->array);
  680. }
  681. static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
  682. {
  683. uint8_t i;
  684. uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
  685. /*
  686. * We only support writing HEVCDecoderConfigurationRecord version 1.
  687. */
  688. hvcc->configurationVersion = 1;
  689. /*
  690. * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
  691. */
  692. if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
  693. hvcc->min_spatial_segmentation_idc = 0;
  694. /*
  695. * parallelismType indicates the type of parallelism that is used to meet
  696. * the restrictions imposed by min_spatial_segmentation_idc when the value
  697. * of min_spatial_segmentation_idc is greater than 0.
  698. */
  699. if (!hvcc->min_spatial_segmentation_idc)
  700. hvcc->parallelismType = 0;
  701. /*
  702. * It's unclear how to properly compute these fields, so
  703. * let's always set them to values meaning 'unspecified'.
  704. */
  705. hvcc->avgFrameRate = 0;
  706. hvcc->constantFrameRate = 0;
  707. av_log(NULL, AV_LOG_TRACE, "configurationVersion: %"PRIu8"\n",
  708. hvcc->configurationVersion);
  709. av_log(NULL, AV_LOG_TRACE, "general_profile_space: %"PRIu8"\n",
  710. hvcc->general_profile_space);
  711. av_log(NULL, AV_LOG_TRACE, "general_tier_flag: %"PRIu8"\n",
  712. hvcc->general_tier_flag);
  713. av_log(NULL, AV_LOG_TRACE, "general_profile_idc: %"PRIu8"\n",
  714. hvcc->general_profile_idc);
  715. av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
  716. hvcc->general_profile_compatibility_flags);
  717. av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags: 0x%012"PRIx64"\n",
  718. hvcc->general_constraint_indicator_flags);
  719. av_log(NULL, AV_LOG_TRACE, "general_level_idc: %"PRIu8"\n",
  720. hvcc->general_level_idc);
  721. av_log(NULL, AV_LOG_TRACE, "min_spatial_segmentation_idc: %"PRIu16"\n",
  722. hvcc->min_spatial_segmentation_idc);
  723. av_log(NULL, AV_LOG_TRACE, "parallelismType: %"PRIu8"\n",
  724. hvcc->parallelismType);
  725. av_log(NULL, AV_LOG_TRACE, "chromaFormat: %"PRIu8"\n",
  726. hvcc->chromaFormat);
  727. av_log(NULL, AV_LOG_TRACE, "bitDepthLumaMinus8: %"PRIu8"\n",
  728. hvcc->bitDepthLumaMinus8);
  729. av_log(NULL, AV_LOG_TRACE, "bitDepthChromaMinus8: %"PRIu8"\n",
  730. hvcc->bitDepthChromaMinus8);
  731. av_log(NULL, AV_LOG_TRACE, "avgFrameRate: %"PRIu16"\n",
  732. hvcc->avgFrameRate);
  733. av_log(NULL, AV_LOG_TRACE, "constantFrameRate: %"PRIu8"\n",
  734. hvcc->constantFrameRate);
  735. av_log(NULL, AV_LOG_TRACE, "numTemporalLayers: %"PRIu8"\n",
  736. hvcc->numTemporalLayers);
  737. av_log(NULL, AV_LOG_TRACE, "temporalIdNested: %"PRIu8"\n",
  738. hvcc->temporalIdNested);
  739. av_log(NULL, AV_LOG_TRACE, "lengthSizeMinusOne: %"PRIu8"\n",
  740. hvcc->lengthSizeMinusOne);
  741. av_log(NULL, AV_LOG_TRACE, "numOfArrays: %"PRIu8"\n",
  742. hvcc->numOfArrays);
  743. for (i = 0; i < hvcc->numOfArrays; i++) {
  744. av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]: %"PRIu8"\n",
  745. i, hvcc->array[i].array_completeness);
  746. av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]: %"PRIu8"\n",
  747. i, hvcc->array[i].NAL_unit_type);
  748. av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]: %"PRIu16"\n",
  749. i, hvcc->array[i].numNalus);
  750. for (j = 0; j < hvcc->array[i].numNalus; j++)
  751. av_log(NULL, AV_LOG_TRACE,
  752. "nalUnitLength[%"PRIu8"][%"PRIu16"]: %"PRIu16"\n",
  753. i, j, hvcc->array[i].nalUnitLength[j]);
  754. }
  755. /*
  756. * We need at least one of each: VPS, SPS and PPS.
  757. */
  758. for (i = 0; i < hvcc->numOfArrays; i++)
  759. switch (hvcc->array[i].NAL_unit_type) {
  760. case HEVC_NAL_VPS:
  761. vps_count += hvcc->array[i].numNalus;
  762. break;
  763. case HEVC_NAL_SPS:
  764. sps_count += hvcc->array[i].numNalus;
  765. break;
  766. case HEVC_NAL_PPS:
  767. pps_count += hvcc->array[i].numNalus;
  768. break;
  769. default:
  770. break;
  771. }
  772. if (!vps_count || vps_count > HEVC_MAX_VPS_COUNT ||
  773. !sps_count || sps_count > HEVC_MAX_SPS_COUNT ||
  774. !pps_count || pps_count > HEVC_MAX_PPS_COUNT)
  775. return AVERROR_INVALIDDATA;
  776. /* unsigned int(8) configurationVersion = 1; */
  777. avio_w8(pb, hvcc->configurationVersion);
  778. /*
  779. * unsigned int(2) general_profile_space;
  780. * unsigned int(1) general_tier_flag;
  781. * unsigned int(5) general_profile_idc;
  782. */
  783. avio_w8(pb, hvcc->general_profile_space << 6 |
  784. hvcc->general_tier_flag << 5 |
  785. hvcc->general_profile_idc);
  786. /* unsigned int(32) general_profile_compatibility_flags; */
  787. avio_wb32(pb, hvcc->general_profile_compatibility_flags);
  788. /* unsigned int(48) general_constraint_indicator_flags; */
  789. avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
  790. avio_wb16(pb, hvcc->general_constraint_indicator_flags);
  791. /* unsigned int(8) general_level_idc; */
  792. avio_w8(pb, hvcc->general_level_idc);
  793. /*
  794. * bit(4) reserved = ‘1111’b;
  795. * unsigned int(12) min_spatial_segmentation_idc;
  796. */
  797. avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
  798. /*
  799. * bit(6) reserved = ‘111111’b;
  800. * unsigned int(2) parallelismType;
  801. */
  802. avio_w8(pb, hvcc->parallelismType | 0xfc);
  803. /*
  804. * bit(6) reserved = ‘111111’b;
  805. * unsigned int(2) chromaFormat;
  806. */
  807. avio_w8(pb, hvcc->chromaFormat | 0xfc);
  808. /*
  809. * bit(5) reserved = ‘11111’b;
  810. * unsigned int(3) bitDepthLumaMinus8;
  811. */
  812. avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
  813. /*
  814. * bit(5) reserved = ‘11111’b;
  815. * unsigned int(3) bitDepthChromaMinus8;
  816. */
  817. avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
  818. /* bit(16) avgFrameRate; */
  819. avio_wb16(pb, hvcc->avgFrameRate);
  820. /*
  821. * bit(2) constantFrameRate;
  822. * bit(3) numTemporalLayers;
  823. * bit(1) temporalIdNested;
  824. * unsigned int(2) lengthSizeMinusOne;
  825. */
  826. avio_w8(pb, hvcc->constantFrameRate << 6 |
  827. hvcc->numTemporalLayers << 3 |
  828. hvcc->temporalIdNested << 2 |
  829. hvcc->lengthSizeMinusOne);
  830. /* unsigned int(8) numOfArrays; */
  831. avio_w8(pb, hvcc->numOfArrays);
  832. for (i = 0; i < hvcc->numOfArrays; i++) {
  833. /*
  834. * bit(1) array_completeness;
  835. * unsigned int(1) reserved = 0;
  836. * unsigned int(6) NAL_unit_type;
  837. */
  838. avio_w8(pb, hvcc->array[i].array_completeness << 7 |
  839. hvcc->array[i].NAL_unit_type & 0x3f);
  840. /* unsigned int(16) numNalus; */
  841. avio_wb16(pb, hvcc->array[i].numNalus);
  842. for (j = 0; j < hvcc->array[i].numNalus; j++) {
  843. /* unsigned int(16) nalUnitLength; */
  844. avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
  845. /* bit(8*nalUnitLength) nalUnit; */
  846. avio_write(pb, hvcc->array[i].nalUnit[j],
  847. hvcc->array[i].nalUnitLength[j]);
  848. }
  849. }
  850. return 0;
  851. }
  852. int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
  853. int size, int filter_ps, int *ps_count)
  854. {
  855. int num_ps = 0, ret = 0;
  856. uint8_t *buf, *end, *start = NULL;
  857. if (!filter_ps) {
  858. ret = ff_avc_parse_nal_units(pb, buf_in, size);
  859. goto end;
  860. }
  861. ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
  862. if (ret < 0)
  863. goto end;
  864. ret = 0;
  865. buf = start;
  866. end = start + size;
  867. while (end - buf > 4) {
  868. uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
  869. uint8_t type = (buf[4] >> 1) & 0x3f;
  870. buf += 4;
  871. switch (type) {
  872. case HEVC_NAL_VPS:
  873. case HEVC_NAL_SPS:
  874. case HEVC_NAL_PPS:
  875. num_ps++;
  876. break;
  877. default:
  878. ret += 4 + len;
  879. avio_wb32(pb, len);
  880. avio_write(pb, buf, len);
  881. break;
  882. }
  883. buf += len;
  884. }
  885. end:
  886. av_free(start);
  887. if (ps_count)
  888. *ps_count = num_ps;
  889. return ret;
  890. }
  891. int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
  892. int *size, int filter_ps, int *ps_count)
  893. {
  894. AVIOContext *pb;
  895. int ret;
  896. ret = avio_open_dyn_buf(&pb);
  897. if (ret < 0)
  898. return ret;
  899. ret = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
  900. *size = avio_close_dyn_buf(pb, buf_out);
  901. return ret;
  902. }
  903. int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
  904. int size, int ps_array_completeness)
  905. {
  906. int ret = 0;
  907. uint8_t *buf, *end, *start = NULL;
  908. HEVCDecoderConfigurationRecord hvcc;
  909. hvcc_init(&hvcc);
  910. if (size < 6) {
  911. /* We can't write a valid hvcC from the provided data */
  912. ret = AVERROR_INVALIDDATA;
  913. goto end;
  914. } else if (*data == 1) {
  915. /* Data is already hvcC-formatted */
  916. avio_write(pb, data, size);
  917. goto end;
  918. } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
  919. /* Not a valid Annex B start code prefix */
  920. ret = AVERROR_INVALIDDATA;
  921. goto end;
  922. }
  923. ret = ff_avc_parse_nal_units_buf(data, &start, &size);
  924. if (ret < 0)
  925. goto end;
  926. buf = start;
  927. end = start + size;
  928. while (end - buf > 4) {
  929. uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
  930. uint8_t type = (buf[4] >> 1) & 0x3f;
  931. buf += 4;
  932. switch (type) {
  933. case HEVC_NAL_VPS:
  934. case HEVC_NAL_SPS:
  935. case HEVC_NAL_PPS:
  936. case HEVC_NAL_SEI_PREFIX:
  937. case HEVC_NAL_SEI_SUFFIX:
  938. ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
  939. if (ret < 0)
  940. goto end;
  941. break;
  942. default:
  943. break;
  944. }
  945. buf += len;
  946. }
  947. ret = hvcc_write(pb, &hvcc);
  948. end:
  949. hvcc_close(&hvcc);
  950. av_free(start);
  951. return ret;
  952. }