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.

1149 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 int 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 (cpb_cnt_minus1 > 31)
  220. return AVERROR_INVALIDDATA;
  221. }
  222. if (nal_hrd_parameters_present_flag)
  223. skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
  224. sub_pic_hrd_params_present_flag);
  225. if (vcl_hrd_parameters_present_flag)
  226. skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1,
  227. sub_pic_hrd_params_present_flag);
  228. }
  229. return 0;
  230. }
  231. static void skip_timing_info(GetBitContext *gb)
  232. {
  233. skip_bits_long(gb, 32); // num_units_in_tick
  234. skip_bits_long(gb, 32); // time_scale
  235. if (get_bits1(gb)) // poc_proportional_to_timing_flag
  236. get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1
  237. }
  238. static void hvcc_parse_vui(GetBitContext *gb,
  239. HEVCDecoderConfigurationRecord *hvcc,
  240. unsigned int max_sub_layers_minus1)
  241. {
  242. unsigned int min_spatial_segmentation_idc;
  243. if (get_bits1(gb)) // aspect_ratio_info_present_flag
  244. if (get_bits(gb, 8) == 255) // aspect_ratio_idc
  245. skip_bits_long(gb, 32); // sar_width u(16), sar_height u(16)
  246. if (get_bits1(gb)) // overscan_info_present_flag
  247. skip_bits1(gb); // overscan_appropriate_flag
  248. if (get_bits1(gb)) { // video_signal_type_present_flag
  249. skip_bits(gb, 4); // video_format u(3), video_full_range_flag u(1)
  250. if (get_bits1(gb)) // colour_description_present_flag
  251. /*
  252. * colour_primaries u(8)
  253. * transfer_characteristics u(8)
  254. * matrix_coeffs u(8)
  255. */
  256. skip_bits(gb, 24);
  257. }
  258. if (get_bits1(gb)) { // chroma_loc_info_present_flag
  259. get_ue_golomb_long(gb); // chroma_sample_loc_type_top_field
  260. get_ue_golomb_long(gb); // chroma_sample_loc_type_bottom_field
  261. }
  262. /*
  263. * neutral_chroma_indication_flag u(1)
  264. * field_seq_flag u(1)
  265. * frame_field_info_present_flag u(1)
  266. */
  267. skip_bits(gb, 3);
  268. if (get_bits1(gb)) { // default_display_window_flag
  269. get_ue_golomb_long(gb); // def_disp_win_left_offset
  270. get_ue_golomb_long(gb); // def_disp_win_right_offset
  271. get_ue_golomb_long(gb); // def_disp_win_top_offset
  272. get_ue_golomb_long(gb); // def_disp_win_bottom_offset
  273. }
  274. if (get_bits1(gb)) { // vui_timing_info_present_flag
  275. skip_timing_info(gb);
  276. if (get_bits1(gb)) // vui_hrd_parameters_present_flag
  277. skip_hrd_parameters(gb, 1, max_sub_layers_minus1);
  278. }
  279. if (get_bits1(gb)) { // bitstream_restriction_flag
  280. /*
  281. * tiles_fixed_structure_flag u(1)
  282. * motion_vectors_over_pic_boundaries_flag u(1)
  283. * restricted_ref_pic_lists_flag u(1)
  284. */
  285. skip_bits(gb, 3);
  286. min_spatial_segmentation_idc = get_ue_golomb_long(gb);
  287. /*
  288. * unsigned int(12) min_spatial_segmentation_idc;
  289. *
  290. * The min_spatial_segmentation_idc indication must indicate a level of
  291. * spatial segmentation equal to or less than the lowest level of
  292. * spatial segmentation indicated in all the parameter sets.
  293. */
  294. hvcc->min_spatial_segmentation_idc = FFMIN(hvcc->min_spatial_segmentation_idc,
  295. min_spatial_segmentation_idc);
  296. get_ue_golomb_long(gb); // max_bytes_per_pic_denom
  297. get_ue_golomb_long(gb); // max_bits_per_min_cu_denom
  298. get_ue_golomb_long(gb); // log2_max_mv_length_horizontal
  299. get_ue_golomb_long(gb); // log2_max_mv_length_vertical
  300. }
  301. }
  302. static void skip_sub_layer_ordering_info(GetBitContext *gb)
  303. {
  304. get_ue_golomb_long(gb); // max_dec_pic_buffering_minus1
  305. get_ue_golomb_long(gb); // max_num_reorder_pics
  306. get_ue_golomb_long(gb); // max_latency_increase_plus1
  307. }
  308. static int hvcc_parse_vps(GetBitContext *gb,
  309. HEVCDecoderConfigurationRecord *hvcc)
  310. {
  311. unsigned int vps_max_sub_layers_minus1;
  312. /*
  313. * vps_video_parameter_set_id u(4)
  314. * vps_reserved_three_2bits u(2)
  315. * vps_max_layers_minus1 u(6)
  316. */
  317. skip_bits(gb, 12);
  318. vps_max_sub_layers_minus1 = get_bits(gb, 3);
  319. /*
  320. * numTemporalLayers greater than 1 indicates that the stream to which this
  321. * configuration record applies is temporally scalable and the contained
  322. * number of temporal layers (also referred to as temporal sub-layer or
  323. * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
  324. * indicates that the stream is not temporally scalable. Value 0 indicates
  325. * that it is unknown whether the stream is temporally scalable.
  326. */
  327. hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
  328. vps_max_sub_layers_minus1 + 1);
  329. /*
  330. * vps_temporal_id_nesting_flag u(1)
  331. * vps_reserved_0xffff_16bits u(16)
  332. */
  333. skip_bits(gb, 17);
  334. hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1);
  335. /* nothing useful for hvcC past this point */
  336. return 0;
  337. }
  338. static void skip_scaling_list_data(GetBitContext *gb)
  339. {
  340. int i, j, k, num_coeffs;
  341. for (i = 0; i < 4; i++)
  342. for (j = 0; j < (i == 3 ? 2 : 6); j++)
  343. if (!get_bits1(gb)) // scaling_list_pred_mode_flag[i][j]
  344. get_ue_golomb_long(gb); // scaling_list_pred_matrix_id_delta[i][j]
  345. else {
  346. num_coeffs = FFMIN(64, 1 << (4 + (i << 1)));
  347. if (i > 1)
  348. get_se_golomb_long(gb); // scaling_list_dc_coef_minus8[i-2][j]
  349. for (k = 0; k < num_coeffs; k++)
  350. get_se_golomb_long(gb); // scaling_list_delta_coef
  351. }
  352. }
  353. static int parse_rps(GetBitContext *gb, unsigned int rps_idx,
  354. unsigned int num_rps,
  355. unsigned int num_delta_pocs[MAX_SHORT_TERM_RPS_COUNT])
  356. {
  357. unsigned int i;
  358. if (rps_idx && get_bits1(gb)) { // inter_ref_pic_set_prediction_flag
  359. /* this should only happen for slice headers, and this isn't one */
  360. if (rps_idx >= num_rps)
  361. return AVERROR_INVALIDDATA;
  362. skip_bits1 (gb); // delta_rps_sign
  363. get_ue_golomb_long(gb); // abs_delta_rps_minus1
  364. num_delta_pocs[rps_idx] = 0;
  365. /*
  366. * From libavcodec/hevc_ps.c:
  367. *
  368. * if (is_slice_header) {
  369. * //foo
  370. * } else
  371. * rps_ridx = &sps->st_rps[rps - sps->st_rps - 1];
  372. *
  373. * where:
  374. * rps: &sps->st_rps[rps_idx]
  375. * sps->st_rps: &sps->st_rps[0]
  376. * is_slice_header: rps_idx == num_rps
  377. *
  378. * thus:
  379. * if (num_rps != rps_idx)
  380. * rps_ridx = &sps->st_rps[rps_idx - 1];
  381. *
  382. * NumDeltaPocs[RefRpsIdx]: num_delta_pocs[rps_idx - 1]
  383. */
  384. for (i = 0; i <= num_delta_pocs[rps_idx - 1]; i++) {
  385. uint8_t use_delta_flag = 0;
  386. uint8_t used_by_curr_pic_flag = get_bits1(gb);
  387. if (!used_by_curr_pic_flag)
  388. use_delta_flag = get_bits1(gb);
  389. if (used_by_curr_pic_flag || use_delta_flag)
  390. num_delta_pocs[rps_idx]++;
  391. }
  392. } else {
  393. unsigned int num_negative_pics = get_ue_golomb_long(gb);
  394. unsigned int num_positive_pics = get_ue_golomb_long(gb);
  395. if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > get_bits_left(gb))
  396. return AVERROR_INVALIDDATA;
  397. num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics;
  398. for (i = 0; i < num_negative_pics; i++) {
  399. get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx]
  400. skip_bits1 (gb); // used_by_curr_pic_s0_flag[rps_idx]
  401. }
  402. for (i = 0; i < num_positive_pics; i++) {
  403. get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx]
  404. skip_bits1 (gb); // used_by_curr_pic_s1_flag[rps_idx]
  405. }
  406. }
  407. return 0;
  408. }
  409. static int hvcc_parse_sps(GetBitContext *gb,
  410. HEVCDecoderConfigurationRecord *hvcc)
  411. {
  412. unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4;
  413. unsigned int num_short_term_ref_pic_sets, num_delta_pocs[MAX_SHORT_TERM_RPS_COUNT];
  414. skip_bits(gb, 4); // sps_video_parameter_set_id
  415. sps_max_sub_layers_minus1 = get_bits (gb, 3);
  416. /*
  417. * numTemporalLayers greater than 1 indicates that the stream to which this
  418. * configuration record applies is temporally scalable and the contained
  419. * number of temporal layers (also referred to as temporal sub-layer or
  420. * sub-layer in ISO/IEC 23008-2) is equal to numTemporalLayers. Value 1
  421. * indicates that the stream is not temporally scalable. Value 0 indicates
  422. * that it is unknown whether the stream is temporally scalable.
  423. */
  424. hvcc->numTemporalLayers = FFMAX(hvcc->numTemporalLayers,
  425. sps_max_sub_layers_minus1 + 1);
  426. hvcc->temporalIdNested = get_bits1(gb);
  427. hvcc_parse_ptl(gb, hvcc, sps_max_sub_layers_minus1);
  428. get_ue_golomb_long(gb); // sps_seq_parameter_set_id
  429. hvcc->chromaFormat = get_ue_golomb_long(gb);
  430. if (hvcc->chromaFormat == 3)
  431. skip_bits1(gb); // separate_colour_plane_flag
  432. get_ue_golomb_long(gb); // pic_width_in_luma_samples
  433. get_ue_golomb_long(gb); // pic_height_in_luma_samples
  434. if (get_bits1(gb)) { // conformance_window_flag
  435. get_ue_golomb_long(gb); // conf_win_left_offset
  436. get_ue_golomb_long(gb); // conf_win_right_offset
  437. get_ue_golomb_long(gb); // conf_win_top_offset
  438. get_ue_golomb_long(gb); // conf_win_bottom_offset
  439. }
  440. hvcc->bitDepthLumaMinus8 = get_ue_golomb_long(gb);
  441. hvcc->bitDepthChromaMinus8 = get_ue_golomb_long(gb);
  442. log2_max_pic_order_cnt_lsb_minus4 = get_ue_golomb_long(gb);
  443. /* sps_sub_layer_ordering_info_present_flag */
  444. i = get_bits1(gb) ? 0 : sps_max_sub_layers_minus1;
  445. for (; i <= sps_max_sub_layers_minus1; i++)
  446. skip_sub_layer_ordering_info(gb);
  447. get_ue_golomb_long(gb); // log2_min_luma_coding_block_size_minus3
  448. get_ue_golomb_long(gb); // log2_diff_max_min_luma_coding_block_size
  449. get_ue_golomb_long(gb); // log2_min_transform_block_size_minus2
  450. get_ue_golomb_long(gb); // log2_diff_max_min_transform_block_size
  451. get_ue_golomb_long(gb); // max_transform_hierarchy_depth_inter
  452. get_ue_golomb_long(gb); // max_transform_hierarchy_depth_intra
  453. if (get_bits1(gb) && // scaling_list_enabled_flag
  454. get_bits1(gb)) // sps_scaling_list_data_present_flag
  455. skip_scaling_list_data(gb);
  456. skip_bits1(gb); // amp_enabled_flag
  457. skip_bits1(gb); // sample_adaptive_offset_enabled_flag
  458. if (get_bits1(gb)) { // pcm_enabled_flag
  459. skip_bits (gb, 4); // pcm_sample_bit_depth_luma_minus1
  460. skip_bits (gb, 4); // pcm_sample_bit_depth_chroma_minus1
  461. get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3
  462. get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size
  463. skip_bits1 (gb); // pcm_loop_filter_disabled_flag
  464. }
  465. num_short_term_ref_pic_sets = get_ue_golomb_long(gb);
  466. if (num_short_term_ref_pic_sets > MAX_SHORT_TERM_RPS_COUNT)
  467. return AVERROR_INVALIDDATA;
  468. for (i = 0; i < num_short_term_ref_pic_sets; i++) {
  469. int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs);
  470. if (ret < 0)
  471. return ret;
  472. }
  473. if (get_bits1(gb)) { // long_term_ref_pics_present_flag
  474. for (i = 0; i < get_ue_golomb_long(gb); i++) { // num_long_term_ref_pics_sps
  475. int len = FFMIN(log2_max_pic_order_cnt_lsb_minus4 + 4, 16);
  476. skip_bits (gb, len); // lt_ref_pic_poc_lsb_sps[i]
  477. skip_bits1(gb); // used_by_curr_pic_lt_sps_flag[i]
  478. }
  479. }
  480. skip_bits1(gb); // sps_temporal_mvp_enabled_flag
  481. skip_bits1(gb); // strong_intra_smoothing_enabled_flag
  482. if (get_bits1(gb)) // vui_parameters_present_flag
  483. hvcc_parse_vui(gb, hvcc, sps_max_sub_layers_minus1);
  484. /* nothing useful for hvcC past this point */
  485. return 0;
  486. }
  487. static int hvcc_parse_pps(GetBitContext *gb,
  488. HEVCDecoderConfigurationRecord *hvcc)
  489. {
  490. uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag;
  491. get_ue_golomb_long(gb); // pps_pic_parameter_set_id
  492. get_ue_golomb_long(gb); // pps_seq_parameter_set_id
  493. /*
  494. * dependent_slice_segments_enabled_flag u(1)
  495. * output_flag_present_flag u(1)
  496. * num_extra_slice_header_bits u(3)
  497. * sign_data_hiding_enabled_flag u(1)
  498. * cabac_init_present_flag u(1)
  499. */
  500. skip_bits(gb, 7);
  501. get_ue_golomb_long(gb); // num_ref_idx_l0_default_active_minus1
  502. get_ue_golomb_long(gb); // num_ref_idx_l1_default_active_minus1
  503. get_se_golomb_long(gb); // init_qp_minus26
  504. /*
  505. * constrained_intra_pred_flag u(1)
  506. * transform_skip_enabled_flag u(1)
  507. */
  508. skip_bits(gb, 2);
  509. if (get_bits1(gb)) // cu_qp_delta_enabled_flag
  510. get_ue_golomb_long(gb); // diff_cu_qp_delta_depth
  511. get_se_golomb_long(gb); // pps_cb_qp_offset
  512. get_se_golomb_long(gb); // pps_cr_qp_offset
  513. /*
  514. * weighted_pred_flag u(1)
  515. * weighted_bipred_flag u(1)
  516. * transquant_bypass_enabled_flag u(1)
  517. */
  518. skip_bits(gb, 3);
  519. tiles_enabled_flag = get_bits1(gb);
  520. entropy_coding_sync_enabled_flag = get_bits1(gb);
  521. if (entropy_coding_sync_enabled_flag && tiles_enabled_flag)
  522. hvcc->parallelismType = 0; // mixed-type parallel decoding
  523. else if (entropy_coding_sync_enabled_flag)
  524. hvcc->parallelismType = 3; // wavefront-based parallel decoding
  525. else if (tiles_enabled_flag)
  526. hvcc->parallelismType = 2; // tile-based parallel decoding
  527. else
  528. hvcc->parallelismType = 1; // slice-based parallel decoding
  529. /* nothing useful for hvcC past this point */
  530. return 0;
  531. }
  532. static uint8_t *nal_unit_extract_rbsp(const uint8_t *src, uint32_t src_len,
  533. uint32_t *dst_len)
  534. {
  535. uint8_t *dst;
  536. uint32_t i, len;
  537. dst = av_malloc(src_len);
  538. if (!dst)
  539. return NULL;
  540. /* NAL unit header (2 bytes) */
  541. i = len = 0;
  542. while (i < 2 && i < src_len)
  543. dst[len++] = src[i++];
  544. while (i + 2 < src_len)
  545. if (!src[i] && !src[i + 1] && src[i + 2] == 3) {
  546. dst[len++] = src[i++];
  547. dst[len++] = src[i++];
  548. i++; // remove emulation_prevention_three_byte
  549. } else
  550. dst[len++] = src[i++];
  551. while (i < src_len)
  552. dst[len++] = src[i++];
  553. *dst_len = len;
  554. return dst;
  555. }
  556. static void nal_unit_parse_header(GetBitContext *gb, uint8_t *nal_type)
  557. {
  558. skip_bits1(gb); // forbidden_zero_bit
  559. *nal_type = get_bits(gb, 6);
  560. /*
  561. * nuh_layer_id u(6)
  562. * nuh_temporal_id_plus1 u(3)
  563. */
  564. skip_bits(gb, 9);
  565. }
  566. static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
  567. uint8_t nal_type, int ps_array_completeness,
  568. HEVCDecoderConfigurationRecord *hvcc)
  569. {
  570. int ret;
  571. uint8_t index;
  572. uint16_t numNalus;
  573. HVCCNALUnitArray *array;
  574. for (index = 0; index < hvcc->numOfArrays; index++)
  575. if (hvcc->array[index].NAL_unit_type == nal_type)
  576. break;
  577. if (index >= hvcc->numOfArrays) {
  578. uint8_t i;
  579. ret = av_reallocp_array(&hvcc->array, index + 1, sizeof(HVCCNALUnitArray));
  580. if (ret < 0)
  581. return ret;
  582. for (i = hvcc->numOfArrays; i <= index; i++)
  583. memset(&hvcc->array[i], 0, sizeof(HVCCNALUnitArray));
  584. hvcc->numOfArrays = index + 1;
  585. }
  586. array = &hvcc->array[index];
  587. numNalus = array->numNalus;
  588. ret = av_reallocp_array(&array->nalUnit, numNalus + 1, sizeof(uint8_t*));
  589. if (ret < 0)
  590. return ret;
  591. ret = av_reallocp_array(&array->nalUnitLength, numNalus + 1, sizeof(uint16_t));
  592. if (ret < 0)
  593. return ret;
  594. array->nalUnit [numNalus] = nal_buf;
  595. array->nalUnitLength[numNalus] = nal_size;
  596. array->NAL_unit_type = nal_type;
  597. array->numNalus++;
  598. /*
  599. * When the sample entry name is ‘hvc1’, the default and mandatory value of
  600. * array_completeness is 1 for arrays of all types of parameter sets, and 0
  601. * for all other arrays. When the sample entry name is ‘hev1’, the default
  602. * value of array_completeness is 0 for all arrays.
  603. */
  604. if (nal_type == NAL_VPS || nal_type == NAL_SPS || nal_type == NAL_PPS)
  605. array->array_completeness = ps_array_completeness;
  606. return 0;
  607. }
  608. static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size,
  609. int ps_array_completeness,
  610. HEVCDecoderConfigurationRecord *hvcc)
  611. {
  612. int ret = 0;
  613. GetBitContext gbc;
  614. uint8_t nal_type;
  615. uint8_t *rbsp_buf;
  616. uint32_t rbsp_size;
  617. rbsp_buf = nal_unit_extract_rbsp(nal_buf, nal_size, &rbsp_size);
  618. if (!rbsp_buf) {
  619. ret = AVERROR(ENOMEM);
  620. goto end;
  621. }
  622. ret = init_get_bits8(&gbc, rbsp_buf, rbsp_size);
  623. if (ret < 0)
  624. goto end;
  625. nal_unit_parse_header(&gbc, &nal_type);
  626. /*
  627. * Note: only 'declarative' SEI messages are allowed in
  628. * hvcC. Perhaps the SEI playload type should be checked
  629. * and non-declarative SEI messages discarded?
  630. */
  631. switch (nal_type) {
  632. case NAL_VPS:
  633. case NAL_SPS:
  634. case NAL_PPS:
  635. case NAL_SEI_PREFIX:
  636. case NAL_SEI_SUFFIX:
  637. ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type,
  638. ps_array_completeness, hvcc);
  639. if (ret < 0)
  640. goto end;
  641. else if (nal_type == NAL_VPS)
  642. ret = hvcc_parse_vps(&gbc, hvcc);
  643. else if (nal_type == NAL_SPS)
  644. ret = hvcc_parse_sps(&gbc, hvcc);
  645. else if (nal_type == NAL_PPS)
  646. ret = hvcc_parse_pps(&gbc, hvcc);
  647. if (ret < 0)
  648. goto end;
  649. break;
  650. default:
  651. ret = AVERROR_INVALIDDATA;
  652. goto end;
  653. }
  654. end:
  655. av_free(rbsp_buf);
  656. return ret;
  657. }
  658. static void hvcc_init(HEVCDecoderConfigurationRecord *hvcc)
  659. {
  660. memset(hvcc, 0, sizeof(HEVCDecoderConfigurationRecord));
  661. hvcc->configurationVersion = 1;
  662. hvcc->lengthSizeMinusOne = 3; // 4 bytes
  663. /*
  664. * The following fields have all their valid bits set by default,
  665. * the ProfileTierLevel parsing code will unset them when needed.
  666. */
  667. hvcc->general_profile_compatibility_flags = 0xffffffff;
  668. hvcc->general_constraint_indicator_flags = 0xffffffffffff;
  669. /*
  670. * Initialize this field with an invalid value which can be used to detect
  671. * whether we didn't see any VUI (in which case it should be reset to zero).
  672. */
  673. hvcc->min_spatial_segmentation_idc = MAX_SPATIAL_SEGMENTATION + 1;
  674. }
  675. static void hvcc_close(HEVCDecoderConfigurationRecord *hvcc)
  676. {
  677. uint8_t i;
  678. for (i = 0; i < hvcc->numOfArrays; i++) {
  679. hvcc->array[i].numNalus = 0;
  680. av_freep(&hvcc->array[i].nalUnit);
  681. av_freep(&hvcc->array[i].nalUnitLength);
  682. }
  683. hvcc->numOfArrays = 0;
  684. av_freep(&hvcc->array);
  685. }
  686. static int hvcc_write(AVIOContext *pb, HEVCDecoderConfigurationRecord *hvcc)
  687. {
  688. uint8_t i;
  689. uint16_t j, vps_count = 0, sps_count = 0, pps_count = 0;
  690. /*
  691. * We only support writing HEVCDecoderConfigurationRecord version 1.
  692. */
  693. hvcc->configurationVersion = 1;
  694. /*
  695. * If min_spatial_segmentation_idc is invalid, reset to 0 (unspecified).
  696. */
  697. if (hvcc->min_spatial_segmentation_idc > MAX_SPATIAL_SEGMENTATION)
  698. hvcc->min_spatial_segmentation_idc = 0;
  699. /*
  700. * parallelismType indicates the type of parallelism that is used to meet
  701. * the restrictions imposed by min_spatial_segmentation_idc when the value
  702. * of min_spatial_segmentation_idc is greater than 0.
  703. */
  704. if (!hvcc->min_spatial_segmentation_idc)
  705. hvcc->parallelismType = 0;
  706. /*
  707. * It's unclear how to properly compute these fields, so
  708. * let's always set them to values meaning 'unspecified'.
  709. */
  710. hvcc->avgFrameRate = 0;
  711. hvcc->constantFrameRate = 0;
  712. av_log(NULL, AV_LOG_TRACE, "configurationVersion: %"PRIu8"\n",
  713. hvcc->configurationVersion);
  714. av_log(NULL, AV_LOG_TRACE, "general_profile_space: %"PRIu8"\n",
  715. hvcc->general_profile_space);
  716. av_log(NULL, AV_LOG_TRACE, "general_tier_flag: %"PRIu8"\n",
  717. hvcc->general_tier_flag);
  718. av_log(NULL, AV_LOG_TRACE, "general_profile_idc: %"PRIu8"\n",
  719. hvcc->general_profile_idc);
  720. av_log(NULL, AV_LOG_TRACE, "general_profile_compatibility_flags: 0x%08"PRIx32"\n",
  721. hvcc->general_profile_compatibility_flags);
  722. av_log(NULL, AV_LOG_TRACE, "general_constraint_indicator_flags: 0x%012"PRIx64"\n",
  723. hvcc->general_constraint_indicator_flags);
  724. av_log(NULL, AV_LOG_TRACE, "general_level_idc: %"PRIu8"\n",
  725. hvcc->general_level_idc);
  726. av_log(NULL, AV_LOG_TRACE, "min_spatial_segmentation_idc: %"PRIu16"\n",
  727. hvcc->min_spatial_segmentation_idc);
  728. av_log(NULL, AV_LOG_TRACE, "parallelismType: %"PRIu8"\n",
  729. hvcc->parallelismType);
  730. av_log(NULL, AV_LOG_TRACE, "chromaFormat: %"PRIu8"\n",
  731. hvcc->chromaFormat);
  732. av_log(NULL, AV_LOG_TRACE, "bitDepthLumaMinus8: %"PRIu8"\n",
  733. hvcc->bitDepthLumaMinus8);
  734. av_log(NULL, AV_LOG_TRACE, "bitDepthChromaMinus8: %"PRIu8"\n",
  735. hvcc->bitDepthChromaMinus8);
  736. av_log(NULL, AV_LOG_TRACE, "avgFrameRate: %"PRIu16"\n",
  737. hvcc->avgFrameRate);
  738. av_log(NULL, AV_LOG_TRACE, "constantFrameRate: %"PRIu8"\n",
  739. hvcc->constantFrameRate);
  740. av_log(NULL, AV_LOG_TRACE, "numTemporalLayers: %"PRIu8"\n",
  741. hvcc->numTemporalLayers);
  742. av_log(NULL, AV_LOG_TRACE, "temporalIdNested: %"PRIu8"\n",
  743. hvcc->temporalIdNested);
  744. av_log(NULL, AV_LOG_TRACE, "lengthSizeMinusOne: %"PRIu8"\n",
  745. hvcc->lengthSizeMinusOne);
  746. av_log(NULL, AV_LOG_TRACE, "numOfArrays: %"PRIu8"\n",
  747. hvcc->numOfArrays);
  748. for (i = 0; i < hvcc->numOfArrays; i++) {
  749. av_log(NULL, AV_LOG_TRACE, "array_completeness[%"PRIu8"]: %"PRIu8"\n",
  750. i, hvcc->array[i].array_completeness);
  751. av_log(NULL, AV_LOG_TRACE, "NAL_unit_type[%"PRIu8"]: %"PRIu8"\n",
  752. i, hvcc->array[i].NAL_unit_type);
  753. av_log(NULL, AV_LOG_TRACE, "numNalus[%"PRIu8"]: %"PRIu16"\n",
  754. i, hvcc->array[i].numNalus);
  755. for (j = 0; j < hvcc->array[i].numNalus; j++)
  756. av_log(NULL, AV_LOG_TRACE,
  757. "nalUnitLength[%"PRIu8"][%"PRIu16"]: %"PRIu16"\n",
  758. i, j, hvcc->array[i].nalUnitLength[j]);
  759. }
  760. /*
  761. * We need at least one of each: VPS, SPS and PPS.
  762. */
  763. for (i = 0; i < hvcc->numOfArrays; i++)
  764. switch (hvcc->array[i].NAL_unit_type) {
  765. case NAL_VPS:
  766. vps_count += hvcc->array[i].numNalus;
  767. break;
  768. case NAL_SPS:
  769. sps_count += hvcc->array[i].numNalus;
  770. break;
  771. case NAL_PPS:
  772. pps_count += hvcc->array[i].numNalus;
  773. break;
  774. default:
  775. break;
  776. }
  777. if (!vps_count || vps_count > MAX_VPS_COUNT ||
  778. !sps_count || sps_count > MAX_SPS_COUNT ||
  779. !pps_count || pps_count > MAX_PPS_COUNT)
  780. return AVERROR_INVALIDDATA;
  781. /* unsigned int(8) configurationVersion = 1; */
  782. avio_w8(pb, hvcc->configurationVersion);
  783. /*
  784. * unsigned int(2) general_profile_space;
  785. * unsigned int(1) general_tier_flag;
  786. * unsigned int(5) general_profile_idc;
  787. */
  788. avio_w8(pb, hvcc->general_profile_space << 6 |
  789. hvcc->general_tier_flag << 5 |
  790. hvcc->general_profile_idc);
  791. /* unsigned int(32) general_profile_compatibility_flags; */
  792. avio_wb32(pb, hvcc->general_profile_compatibility_flags);
  793. /* unsigned int(48) general_constraint_indicator_flags; */
  794. avio_wb32(pb, hvcc->general_constraint_indicator_flags >> 16);
  795. avio_wb16(pb, hvcc->general_constraint_indicator_flags);
  796. /* unsigned int(8) general_level_idc; */
  797. avio_w8(pb, hvcc->general_level_idc);
  798. /*
  799. * bit(4) reserved = ‘1111’b;
  800. * unsigned int(12) min_spatial_segmentation_idc;
  801. */
  802. avio_wb16(pb, hvcc->min_spatial_segmentation_idc | 0xf000);
  803. /*
  804. * bit(6) reserved = ‘111111’b;
  805. * unsigned int(2) parallelismType;
  806. */
  807. avio_w8(pb, hvcc->parallelismType | 0xfc);
  808. /*
  809. * bit(6) reserved = ‘111111’b;
  810. * unsigned int(2) chromaFormat;
  811. */
  812. avio_w8(pb, hvcc->chromaFormat | 0xfc);
  813. /*
  814. * bit(5) reserved = ‘11111’b;
  815. * unsigned int(3) bitDepthLumaMinus8;
  816. */
  817. avio_w8(pb, hvcc->bitDepthLumaMinus8 | 0xf8);
  818. /*
  819. * bit(5) reserved = ‘11111’b;
  820. * unsigned int(3) bitDepthChromaMinus8;
  821. */
  822. avio_w8(pb, hvcc->bitDepthChromaMinus8 | 0xf8);
  823. /* bit(16) avgFrameRate; */
  824. avio_wb16(pb, hvcc->avgFrameRate);
  825. /*
  826. * bit(2) constantFrameRate;
  827. * bit(3) numTemporalLayers;
  828. * bit(1) temporalIdNested;
  829. * unsigned int(2) lengthSizeMinusOne;
  830. */
  831. avio_w8(pb, hvcc->constantFrameRate << 6 |
  832. hvcc->numTemporalLayers << 3 |
  833. hvcc->temporalIdNested << 2 |
  834. hvcc->lengthSizeMinusOne);
  835. /* unsigned int(8) numOfArrays; */
  836. avio_w8(pb, hvcc->numOfArrays);
  837. for (i = 0; i < hvcc->numOfArrays; i++) {
  838. /*
  839. * bit(1) array_completeness;
  840. * unsigned int(1) reserved = 0;
  841. * unsigned int(6) NAL_unit_type;
  842. */
  843. avio_w8(pb, hvcc->array[i].array_completeness << 7 |
  844. hvcc->array[i].NAL_unit_type & 0x3f);
  845. /* unsigned int(16) numNalus; */
  846. avio_wb16(pb, hvcc->array[i].numNalus);
  847. for (j = 0; j < hvcc->array[i].numNalus; j++) {
  848. /* unsigned int(16) nalUnitLength; */
  849. avio_wb16(pb, hvcc->array[i].nalUnitLength[j]);
  850. /* bit(8*nalUnitLength) nalUnit; */
  851. avio_write(pb, hvcc->array[i].nalUnit[j],
  852. hvcc->array[i].nalUnitLength[j]);
  853. }
  854. }
  855. return 0;
  856. }
  857. int ff_hevc_annexb2mp4(AVIOContext *pb, const uint8_t *buf_in,
  858. int size, int filter_ps, int *ps_count)
  859. {
  860. int num_ps = 0, ret = 0;
  861. uint8_t *buf, *end, *start = NULL;
  862. if (!filter_ps) {
  863. ret = ff_avc_parse_nal_units(pb, buf_in, size);
  864. goto end;
  865. }
  866. ret = ff_avc_parse_nal_units_buf(buf_in, &start, &size);
  867. if (ret < 0)
  868. goto end;
  869. ret = 0;
  870. buf = start;
  871. end = start + size;
  872. while (end - buf > 4) {
  873. uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
  874. uint8_t type = (buf[4] >> 1) & 0x3f;
  875. buf += 4;
  876. switch (type) {
  877. case NAL_VPS:
  878. case NAL_SPS:
  879. case NAL_PPS:
  880. num_ps++;
  881. break;
  882. default:
  883. ret += 4 + len;
  884. avio_wb32(pb, len);
  885. avio_write(pb, buf, len);
  886. break;
  887. }
  888. buf += len;
  889. }
  890. end:
  891. av_free(start);
  892. if (ps_count)
  893. *ps_count = num_ps;
  894. return ret;
  895. }
  896. int ff_hevc_annexb2mp4_buf(const uint8_t *buf_in, uint8_t **buf_out,
  897. int *size, int filter_ps, int *ps_count)
  898. {
  899. AVIOContext *pb;
  900. int ret;
  901. ret = avio_open_dyn_buf(&pb);
  902. if (ret < 0)
  903. return ret;
  904. ret = ff_hevc_annexb2mp4(pb, buf_in, *size, filter_ps, ps_count);
  905. *size = avio_close_dyn_buf(pb, buf_out);
  906. return ret;
  907. }
  908. int ff_isom_write_hvcc(AVIOContext *pb, const uint8_t *data,
  909. int size, int ps_array_completeness)
  910. {
  911. int ret = 0;
  912. uint8_t *buf, *end, *start = NULL;
  913. HEVCDecoderConfigurationRecord hvcc;
  914. hvcc_init(&hvcc);
  915. if (size < 6) {
  916. /* We can't write a valid hvcC from the provided data */
  917. ret = AVERROR_INVALIDDATA;
  918. goto end;
  919. } else if (*data == 1) {
  920. /* Data is already hvcC-formatted */
  921. avio_write(pb, data, size);
  922. goto end;
  923. } else if (!(AV_RB24(data) == 1 || AV_RB32(data) == 1)) {
  924. /* Not a valid Annex B start code prefix */
  925. ret = AVERROR_INVALIDDATA;
  926. goto end;
  927. }
  928. ret = ff_avc_parse_nal_units_buf(data, &start, &size);
  929. if (ret < 0)
  930. goto end;
  931. buf = start;
  932. end = start + size;
  933. while (end - buf > 4) {
  934. uint32_t len = FFMIN(AV_RB32(buf), end - buf - 4);
  935. uint8_t type = (buf[4] >> 1) & 0x3f;
  936. buf += 4;
  937. switch (type) {
  938. case NAL_VPS:
  939. case NAL_SPS:
  940. case NAL_PPS:
  941. case NAL_SEI_PREFIX:
  942. case NAL_SEI_SUFFIX:
  943. ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc);
  944. if (ret < 0)
  945. goto end;
  946. break;
  947. default:
  948. break;
  949. }
  950. buf += len;
  951. }
  952. ret = hvcc_write(pb, &hvcc);
  953. end:
  954. hvcc_close(&hvcc);
  955. av_free(start);
  956. return ret;
  957. }