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.

1141 lines
38KB

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