develop/utils/rocvideodecode/roc_video_dec.h Source File

develop/utils/rocvideodecode/roc_video_dec.h Source File#

rocDecode: develop/utils/rocvideodecode/roc_video_dec.h Source File
roc_video_dec.h
Go to the documentation of this file.
1 /*
2 Copyright (c) 2023 - 2024 Advanced Micro Devices, Inc. All rights reserved.
3 
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10 
11 The above copyright notice and this permission notice shall be included in
12 all copies or substantial portions of the Software.
13 
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE.
21 */
22 
23 #pragma once
24 
25 #include <assert.h>
26 #include <stdint.h>
27 #include <mutex>
28 #include <vector>
29 #include <string>
30 #include <iostream>
31 #include <sstream>
32 #include <string.h>
33 #include <queue>
34 #include <stdexcept>
35 #include <exception>
36 #include <cstring>
37 #include <unordered_map>
38 #include <chrono>
39 #include <hip/hip_runtime.h>
40 #include "rocdecode.h"
41 #include "rocparser.h"
42 
51 #define MAX_FRAME_NUM 16
52 
53 typedef int (ROCDECAPI *PFNRECONFIGUEFLUSHCALLBACK)(void *, uint32_t, void *);
54 
55 typedef enum SeiAvcHevcPayloadType_enum {
56  SEI_TYPE_TIME_CODE = 136,
57  SEI_TYPE_USER_DATA_UNREGISTERED = 5
58 } SeiAvcHevcPayloadType;
59 
65 } OutputSurfaceMemoryType;
66 
67 #define TOSTR(X) std::to_string(static_cast<int>(X))
68 #define STR(X) std::string(X)
69 
70 #if DBGINFO
71 #define INFO(X) std::clog << "[INF] " << " {" << __func__ <<"} " << " " << X << std::endl;
72 #else
73 #define INFO(X) ;
74 #endif
75 #define ERR(X) std::cerr << "[ERR] " << " {" << __func__ <<"} " << " " << X << std::endl;
76 
77 inline int GetChromaPlaneCount(rocDecVideoSurfaceFormat surface_format) {
78  int num_planes = 1;
79  switch (surface_format) {
82  num_planes = 1;
83  break;
86  num_planes = 2;
87  break;
90  num_planes = 2;
91  break;
92  }
93 
94  return num_planes;
95 };
96 
97 inline float GetChromaHeightFactor(rocDecVideoSurfaceFormat surface_format) {
98  float factor = 0.5;
99  switch (surface_format) {
104  factor = 0.5;
105  break;
108  factor = 1.0;
109  break;
110  }
111 
112  return factor;
113 };
114 
115 
116 class RocVideoDecodeException : public std::exception {
117 public:
118 
119  explicit RocVideoDecodeException(const std::string& message, const int err_code):_message(message), _err_code(err_code) {}
120  explicit RocVideoDecodeException(const std::string& message):_message(message), _err_code(-1) {}
121  virtual const char* what() const throw() override {
122  return _message.c_str();
123  }
124  int Geterror_code() const { return _err_code; }
125 private:
126  std::string _message;
127  int _err_code;
128 };
129 
130 #define ROCDEC_THROW(X, CODE) throw RocVideoDecodeException(" { " + std::string(__func__) + " } " + X , CODE);
131 #define THROW(X) throw RocVideoDecodeException(" { " + std::string(__func__) + " } " + X);
132 
133 #define ROCDEC_API_CALL( rocDecAPI ) \
134  do { \
135  rocDecStatus error_code = rocDecAPI; \
136  if( error_code != ROCDEC_SUCCESS) { \
137  std::ostringstream error_log; \
138  error_log << #rocDecAPI << " returned " << rocDecGetErrorName(error_code) << " at " <<__FILE__ <<":" << __LINE__;\
139  ROCDEC_THROW(error_log.str(), error_code); \
140  } \
141  } while (0)
142 
143 #define HIP_API_CALL( call ) \
144  do { \
145  hipError_t hip_status = call; \
146  if (hip_status != hipSuccess) { \
147  const char *sz_err_name = NULL; \
148  sz_err_name = hipGetErrorName(hip_status); \
149  std::ostringstream error_log; \
150  error_log << "hip API error " << sz_err_name ; \
151  ROCDEC_THROW(error_log.str(), hip_status); \
152  } \
153  } \
154  while (0)
155 
156 
157 struct Rect {
158  int left;
159  int top;
160  int right;
161  int bottom;
162 };
163 
164 struct Dim {
165  int w, h;
166 };
167 
168 static inline int align(int value, int alignment) {
169  return (value + alignment - 1) & ~(alignment - 1);
170 }
171 
172 typedef struct DecFrameBuffer_ {
173  uint8_t *frame_ptr;
174  int64_t pts;
177 
178 
179 typedef struct OutputSurfaceInfoType {
180  uint32_t output_width;
181  uint32_t output_height;
182  uint32_t output_pitch;
183  uint32_t output_vstride;
184  uint32_t chroma_height;
186  uint32_t bytes_per_pixel;
187  uint32_t bit_depth;
188  uint32_t num_chroma_planes;
190  rocDecVideoSurfaceFormat surface_format;
191  OutputSurfaceMemoryType mem_type;
193 
194 typedef struct ReconfigParams_t {
195  PFNRECONFIGUEFLUSHCALLBACK p_fn_reconfigure_flush;
196  void *p_reconfig_user_struct;
197  uint32_t reconfig_flush_mode;
199 
201  public:
216  RocVideoDecoder(int device_id, OutputSurfaceMemoryType out_mem_type, rocDecVideoCodec codec, bool force_zero_latency = false,
217  const Rect *p_crop_rect = nullptr, bool extract_user_SEI_Message = false, uint32_t disp_delay = 0, int max_width = 0, int max_height = 0,
218  uint32_t clk_rate = 1000);
219  ~RocVideoDecoder();
220 
221  rocDecVideoCodec GetCodecId() { return codec_id_; }
222 
223  hipStream_t GetStream() {return hip_stream_;}
224 
228  uint32_t GetWidth() { assert(disp_width_); return disp_width_;}
229 
233  int GetDecodeWidth() { assert(coded_width_); return coded_width_; }
234 
238  uint32_t GetHeight() { assert(disp_height_); return disp_height_; }
239 
243  int GetChromaHeight() { assert(chroma_height_); return chroma_height_; }
244 
248  int GetNumChromaPlanes() { assert(num_chroma_planes_); return num_chroma_planes_; }
249 
253  virtual int GetFrameSize() { assert(disp_width_); return disp_width_ * (disp_height_ + (chroma_height_ * num_chroma_planes_)) * byte_per_pixel_; }
254 
255 
261  uint32_t GetBitDepth() { assert(bitdepth_minus_8_); return (bitdepth_minus_8_ + 8); }
262  uint32_t GetBytePerPixel() { assert(byte_per_pixel_); return byte_per_pixel_; }
266  size_t GetSurfaceSize() { assert(surface_size_); return surface_size_; }
267  uint32_t GetSurfaceStride() { assert(surface_stride_); return surface_stride_; }
268  //RocDecImageFormat GetSubsampling() { return subsampling_; }
275  const char *GetCodecFmtName(rocDecVideoCodec codec_id);
276 
283  const char *GetSurfaceFmtName(rocDecVideoSurfaceFormat surface_format_id);
284 
293 
301  bool SetReconfigParams(ReconfigParams *p_reconfig_params, bool b_force_reconfig_flush = false);
302 
319  virtual int DecodeFrame(const uint8_t *data, size_t size, int pkt_flags, int64_t pts = 0, int *num_decoded_pics = nullptr);
324  virtual uint8_t* GetFrame(int64_t *pts);
325 
334  virtual bool ReleaseFrame(int64_t pTimestamp, bool b_flushing = false);
335 
344  //void SaveImage(std::string output_file_name, void* dev_mem, OutputImageInfo* image_info, bool is_output_RGB = 0);
345 
355  void GetDeviceinfo(std::string &device_name, std::string &gcn_arch_name, int &pci_bus_id, int &pci_domain_id, int &pci_device_id);
356 
365  virtual void SaveFrameToFile(std::string output_file_name, void *surf_mem, OutputSurfaceInfo *surf_info, size_t rgb_image_size = 0);
366 
370  virtual void ResetSaveFrameToFile();
371 
377  int32_t GetNumOfFlushedFrames() { return num_frames_flushed_during_reconfig_;}
378 
382 
383  // Session overhead refers to decoder initialization and deinitialization time
384  void AddDecoderSessionOverHead(std::thread::id session_id, double duration) { session_overhead_[session_id] += duration; }
385  double GetDecoderSessionOverHead(std::thread::id session_id) {
386  if (session_overhead_.find(session_id) != session_overhead_.end()) {
387  return session_overhead_[session_id];
388  } else {
389  return 0;
390  }
391  }
392 
398  bool CodecSupported(int device_id, rocDecVideoCodec codec_id, uint32_t bit_depth);
399 
403  virtual int ReconfigureDecoder(RocdecVideoFormat *p_video_format);
404 
405  protected:
409  static int ROCDECAPI HandleVideoSequenceProc(void *p_user_data, RocdecVideoFormat *p_video_format) { return ((RocVideoDecoder *)p_user_data)->HandleVideoSequence(p_video_format); }
410 
414  static int ROCDECAPI HandlePictureDecodeProc(void *p_user_data, RocdecPicParams *p_pic_params) { return ((RocVideoDecoder *)p_user_data)->HandlePictureDecode(p_pic_params); }
415 
419  static int ROCDECAPI HandlePictureDisplayProc(void *p_user_data, RocdecParserDispInfo *p_disp_info) { return ((RocVideoDecoder *)p_user_data)->HandlePictureDisplay(p_disp_info); }
420 
424  static int ROCDECAPI HandleSEIMessagesProc(void *p_user_data, RocdecSeiMessageInfo *p_sei_message_info) { return ((RocVideoDecoder *)p_user_data)->GetSEIMessage(p_sei_message_info); }
425 
431 
437 
446  int GetSEIMessage(RocdecSeiMessageInfo *p_sei_message_info);
447 
455 
460  bool InitHIP(int device_id);
461 
466  std::chrono::_V2::system_clock::time_point StartTimer();
467 
472  double StopTimer(const std::chrono::_V2::system_clock::time_point &start_time);
473 
474  int num_devices_;
475  int device_id_;
476  RocdecVideoParser rocdec_parser_ = nullptr;
477  rocDecDecoderHandle roc_decoder_ = nullptr;
478  OutputSurfaceMemoryType out_mem_type_ = OUT_SURFACE_MEM_DEV_INTERNAL;
479  bool b_extract_sei_message_ = false;
480  bool b_force_zero_latency_ = false;
481  uint32_t disp_delay_;
482  ReconfigParams *p_reconfig_params_ = nullptr;
483  bool b_force_recofig_flush_ = false;
484  int32_t num_frames_flushed_during_reconfig_ = 0;
485  hipDeviceProp_t hip_dev_prop_;
486  hipStream_t hip_stream_;
487  rocDecVideoCodec codec_id_ = rocDecVideoCodec_NumCodecs;
488  rocDecVideoChromaFormat video_chroma_format_ = rocDecVideoChromaFormat_420;
489  rocDecVideoSurfaceFormat video_surface_format_ = rocDecVideoSurfaceFormat_NV12;
490  RocdecSeiMessageInfo *curr_sei_message_ptr_ = nullptr;
491  RocdecSeiMessageInfo sei_message_display_q_[MAX_FRAME_NUM];
492  RocdecVideoFormat *curr_video_format_ptr_ = nullptr;
493  int output_frame_cnt_ = 0, output_frame_cnt_ret_ = 0;
494  int decoded_pic_cnt_ = 0;
495  int decode_poc_ = 0, pic_num_in_dec_order_[MAX_FRAME_NUM];
496  int num_alloced_frames_ = 0;
497  int last_decode_surf_idx_ = 0;
498  std::ostringstream input_video_info_str_;
499  int bitdepth_minus_8_ = 0;
500  uint32_t byte_per_pixel_ = 1;
501  uint32_t coded_width_ = 0;
502  uint32_t disp_width_ = 0;
503  uint32_t coded_height_ = 0;
504  uint32_t disp_height_ = 0;
505  uint32_t target_width_ = 0;
506  uint32_t target_height_ = 0;
507  int max_width_ = 0, max_height_ = 0;
508  uint32_t chroma_height_ = 0, chroma_width_ = 0;
509  uint32_t num_chroma_planes_ = 0;
510  uint32_t num_components_ = 0;
511  uint32_t surface_stride_ = 0;
512  uint32_t surface_vstride_ = 0, chroma_vstride_ = 0; // vertical stride between planes: used when using internal dev memory
513  size_t surface_size_ = 0;
514  OutputSurfaceInfo output_surface_info_ = {};
515  std::mutex mtx_vp_frame_;
516  std::vector<DecFrameBuffer> vp_frames_; // vector of decoded frames
517  std::queue<DecFrameBuffer> vp_frames_q_;
518  Rect disp_rect_ = {}; // displayable area specified in the bitstream
519  Rect crop_rect_ = {}; // user specified region of interest within diplayable area disp_rect_
520  FILE *fp_sei_ = NULL;
521  FILE *fp_out_ = NULL;
522  bool is_decoder_reconfigured_ = false;
523  std::string current_output_filename = "";
524  uint32_t extra_output_file_count_ = 0;
525  std::thread::id decoder_session_id_; // Decoder session identifier. Used to gather session level stats.
526  std::unordered_map<std::thread::id, double> session_overhead_; // Records session overhead of initialization+deinitialization time. Format is (thread id, duration)
527 };
Definition: roc_video_dec.h:116
Definition: roc_video_dec.h:200
virtual void ResetSaveFrameToFile()
Helper funtion to close a existing file and dump to new file in case of multiple files using same dec...
virtual bool ReleaseFrame(int64_t pTimestamp, bool b_flushing=false)
function to release frame after use by the application: Only used with "OUT_SURFACE_MEM_DEV_INTERNAL"
int FlushAndReconfigure()
Function to force Reconfigure Flush: needed for random seeking to key frames.
void WaitForDecodeCompletion()
Function to wait for the decode completion of the last submitted picture.
int32_t GetNumOfFlushedFrames()
Get the Num Of Flushed Frames from video decoder object.
Definition: roc_video_dec.h:377
const char * GetCodecFmtName(rocDecVideoCodec codec_id)
Get the name of the output format.
uint32_t GetWidth()
Get the output frame width.
Definition: roc_video_dec.h:228
int GetNumChromaPlanes()
This function is used to get the number of chroma planes.
Definition: roc_video_dec.h:248
virtual int ReconfigureDecoder(RocdecVideoFormat *p_video_format)
This function reconfigure decoder if there is a change in sequence params.
static int ROCDECAPI HandlePictureDisplayProc(void *p_user_data, RocdecParserDispInfo *p_disp_info)
Callback function to be registered for getting a callback when a decoded frame is available for displ...
Definition: roc_video_dec.h:419
int HandlePictureDisplay(RocdecParserDispInfo *p_disp_info)
This function gets called after a picture is decoded and available for display. Frames are fetched an...
int GetChromaHeight()
This function is used to get the current chroma height.
Definition: roc_video_dec.h:243
uint32_t GetHeight()
Get the output frame height.
Definition: roc_video_dec.h:238
int GetSEIMessage(RocdecSeiMessageInfo *p_sei_message_info)
This function gets called when all unregistered user SEI messages are parsed for a frame.
uint32_t GetBitDepth()
Get the Bit Depth and BytesPerPixel associated with the pixel format.
Definition: roc_video_dec.h:261
double StopTimer(const std::chrono::_V2::system_clock::time_point &start_time)
Function to get elapsed time.
static int ROCDECAPI HandlePictureDecodeProc(void *p_user_data, RocdecPicParams *p_pic_params)
Callback function to be registered for getting a callback when a decoded frame is ready to be decoded...
Definition: roc_video_dec.h:414
bool InitHIP(int device_id)
Function to Initialize GPU-HIP.
bool ReleaseInternalFrames()
function to release all internal frames and clear the vp_frames_q_ (used with reconfigure): Only used...
virtual uint8_t * GetFrame(int64_t *pts)
This function returns a decoded frame and timestamp. This should be called in a loop fetching all the...
virtual void SaveFrameToFile(std::string output_file_name, void *surf_mem, OutputSurfaceInfo *surf_info, size_t rgb_image_size=0)
Helper function to dump decoded output surface to file.
void GetDeviceinfo(std::string &device_name, std::string &gcn_arch_name, int &pci_bus_id, int &pci_domain_id, int &pci_device_id)
utility function to save image to a file
bool CodecSupported(int device_id, rocDecVideoCodec codec_id, uint32_t bit_depth)
Check if the given Video Codec is supported on the given GPU.
std::chrono::_V2::system_clock::time_point StartTimer()
Function to get start time.
virtual int GetFrameSize()
This function is used to get the current frame size based on pixel format.
Definition: roc_video_dec.h:253
const char * GetSurfaceFmtName(rocDecVideoSurfaceFormat surface_format_id)
function to return the name from surface_format_id
bool GetOutputSurfaceInfo(OutputSurfaceInfo **surface_info)
Get the pointer to the Output Image Info.
size_t GetSurfaceSize()
Functions to get the output surface attributes.
Definition: roc_video_dec.h:266
RocVideoDecoder(int device_id, OutputSurfaceMemoryType out_mem_type, rocDecVideoCodec codec, bool force_zero_latency=false, const Rect *p_crop_rect=nullptr, bool extract_user_SEI_Message=false, uint32_t disp_delay=0, int max_width=0, int max_height=0, uint32_t clk_rate=1000)
Construct a new Roc Video Decoder object.
static int ROCDECAPI HandleSEIMessagesProc(void *p_user_data, RocdecSeiMessageInfo *p_sei_message_info)
Callback function to be registered for getting a callback when all the unregistered user SEI Messages...
Definition: roc_video_dec.h:424
virtual int DecodeFrame(const uint8_t *data, size_t size, int pkt_flags, int64_t pts=0, int *num_decoded_pics=nullptr)
this function decodes a frame and returns the number of frames avalable for display
int GetDecodeWidth()
This function is used to get the actual decode width.
Definition: roc_video_dec.h:233
int HandlePictureDecode(RocdecPicParams *p_pic_params)
This function gets called when a picture is ready to be decoded. cuvidDecodePicture is called from th...
bool SetReconfigParams(ReconfigParams *p_reconfig_params, bool b_force_reconfig_flush=false)
Function to set the Reconfig Params object.
int HandleVideoSequence(RocdecVideoFormat *p_video_format)
This function gets called when a sequence is ready to be decoded. The function also gets called when ...
static int ROCDECAPI HandleVideoSequenceProc(void *p_user_data, RocdecVideoFormat *p_video_format)
Callback function to be registered for getting a callback when decoding of sequence starts.
Definition: roc_video_dec.h:409
OutputSurfaceMemoryType_enum
Definition: roc_video_dec.h:60
@ OUT_SURFACE_MEM_HOST_COPIED
Definition: roc_video_dec.h:63
@ OUT_SURFACE_MEM_DEV_COPIED
Definition: roc_video_dec.h:62
@ OUT_SURFACE_MEM_DEV_INTERNAL
Definition: roc_video_dec.h:61
@ OUT_SURFACE_MEM_NOT_MAPPED
Definition: roc_video_dec.h:64
The AMD rocDecode Library.
@ rocDecVideoCodec_NumCodecs
Definition: rocdecode.h:88
@ rocDecVideoSurfaceFormat_YUV420
Definition: rocdecode.h:110
@ rocDecVideoSurfaceFormat_YUV444_16Bit
Definition: rocdecode.h:108
@ rocDecVideoSurfaceFormat_YUV420_16Bit
Definition: rocdecode.h:111
@ rocDecVideoSurfaceFormat_P016
Definition: rocdecode.h:105
@ rocDecVideoSurfaceFormat_NV12
Definition: rocdecode.h:104
@ rocDecVideoSurfaceFormat_YUV444
Definition: rocdecode.h:107
void * rocDecDecoderHandle
Definition: rocdecode.h:52
@ rocDecVideoChromaFormat_420
Definition: rocdecode.h:123
The AMD rocParser Library.
void * RocdecVideoParser
Definition: rocparser.h:46
Definition: roc_video_dec.h:172
uint8_t * frame_ptr
Definition: roc_video_dec.h:173
int picture_index
Definition: roc_video_dec.h:175
int64_t pts
Definition: roc_video_dec.h:174
Definition: roc_video_dec.h:164
Definition: roc_video_dec.h:179
uint32_t output_vstride
Definition: roc_video_dec.h:183
uint32_t output_pitch
Definition: roc_video_dec.h:182
uint32_t output_height
Definition: roc_video_dec.h:181
uint32_t chroma_height
Definition: roc_video_dec.h:184
uint64_t output_surface_size_in_bytes
Definition: roc_video_dec.h:189
uint32_t num_chroma_planes
Definition: roc_video_dec.h:188
uint32_t bit_depth
Definition: roc_video_dec.h:187
uint32_t bytes_per_pixel
Definition: roc_video_dec.h:186
rocDecVideoSurfaceFormat surface_format
Definition: roc_video_dec.h:190
Rect disp_rect
Definition: roc_video_dec.h:185
uint32_t output_width
Definition: roc_video_dec.h:180
OutputSurfaceMemoryType mem_type
Definition: roc_video_dec.h:191
Definition: roc_video_dec.h:194
Definition: roc_video_dec.h:157
Timing Info struct\Used in rocdecParseVideoData API with PFNVIDDISPLAYCALLBACK pfn_display_picture.
ROCDEC_VIDEO_FORMAT structUsed in Parser callback API.
Definition: rocparser.h:54
Definition: rocdecode.h:1616