qsv_transcode.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /*
  2. * Permission is hereby granted, free of charge, to any person obtaining a copy
  3. * of this software and associated documentation files (the "Software"), to deal
  4. * in the Software without restriction, including without limitation the rights
  5. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  6. * copies of the Software, and to permit persons to whom the Software is
  7. * furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in
  10. * all copies or substantial portions of the Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  15. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. * THE SOFTWARE.
  19. */
  20. /**
  21. * @file Intel QSV-accelerated video transcoding API usage example
  22. * @example qsv_transcode.c
  23. *
  24. * Perform QSV-accelerated transcoding and show to dynamically change
  25. * encoder's options.
  26. *
  27. * Usage: qsv_transcode input_stream codec output_stream initial option
  28. * { frame_number new_option }
  29. * e.g: - qsv_transcode input.mp4 h264_qsv output_h264.mp4 "g 60"
  30. * - qsv_transcode input.mp4 hevc_qsv output_hevc.mp4 "g 60 async_depth 1"
  31. * 100 "g 120"
  32. * (initialize codec with gop_size 60 and change it to 120 after 100
  33. * frames)
  34. */
  35. #include <stdio.h>
  36. #include <errno.h>
  37. #include <libavutil/hwcontext.h>
  38. #include <libavcodec/avcodec.h>
  39. #include <libavformat/avformat.h>
  40. #include <libavutil/opt.h>
  41. static AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
  42. static AVBufferRef *hw_device_ctx = NULL;
  43. static AVCodecContext *decoder_ctx = NULL, *encoder_ctx = NULL;
  44. static int video_stream = -1;
  45. typedef struct DynamicSetting {
  46. int frame_number;
  47. char* optstr;
  48. } DynamicSetting;
  49. static DynamicSetting *dynamic_setting;
  50. static int setting_number;
  51. static int current_setting_number;
  52. static int str_to_dict(char* optstr, AVDictionary **opt)
  53. {
  54. char *key, *value;
  55. if (strlen(optstr) == 0)
  56. return 0;
  57. key = strtok(optstr, " ");
  58. if (key == NULL)
  59. return AVERROR(ENAVAIL);
  60. value = strtok(NULL, " ");
  61. if (value == NULL)
  62. return AVERROR(ENAVAIL);
  63. av_dict_set(opt, key, value, 0);
  64. do {
  65. key = strtok(NULL, " ");
  66. if (key == NULL)
  67. return 0;
  68. value = strtok(NULL, " ");
  69. if (value == NULL)
  70. return AVERROR(ENAVAIL);
  71. av_dict_set(opt, key, value, 0);
  72. } while(1);
  73. }
  74. static int dynamic_set_parameter(AVCodecContext *avctx)
  75. {
  76. AVDictionary *opts = NULL;
  77. int ret = 0;
  78. static int frame_number = 0;
  79. frame_number++;
  80. if (current_setting_number < setting_number &&
  81. frame_number == dynamic_setting[current_setting_number].frame_number) {
  82. AVDictionaryEntry *e = NULL;
  83. ret = str_to_dict(dynamic_setting[current_setting_number++].optstr, &opts);
  84. if (ret < 0) {
  85. fprintf(stderr, "The dynamic parameter is wrong\n");
  86. goto fail;
  87. }
  88. /* Set common option. The dictionary will be freed and replaced
  89. * by a new one containing all options not found in common option list.
  90. * Then this new dictionary is used to set private option. */
  91. if ((ret = av_opt_set_dict(avctx, &opts)) < 0)
  92. goto fail;
  93. /* Set codec specific option */
  94. if ((ret = av_opt_set_dict(avctx->priv_data, &opts)) < 0)
  95. goto fail;
  96. /* There is no "framerate" option in commom option list. Use "-r" to set
  97. * framerate, which is compatible with ffmpeg commandline. The video is
  98. * assumed to be average frame rate, so set time_base to 1/framerate. */
  99. e = av_dict_get(opts, "r", NULL, 0);
  100. if (e) {
  101. avctx->framerate = av_d2q(atof(e->value), INT_MAX);
  102. encoder_ctx->time_base = av_inv_q(encoder_ctx->framerate);
  103. }
  104. }
  105. fail:
  106. av_dict_free(&opts);
  107. return ret;
  108. }
  109. static int get_format(AVCodecContext *avctx, const enum AVPixelFormat *pix_fmts)
  110. {
  111. while (*pix_fmts != AV_PIX_FMT_NONE) {
  112. if (*pix_fmts == AV_PIX_FMT_QSV) {
  113. return AV_PIX_FMT_QSV;
  114. }
  115. pix_fmts++;
  116. }
  117. fprintf(stderr, "The QSV pixel format not offered in get_format()\n");
  118. return AV_PIX_FMT_NONE;
  119. }
  120. static int open_input_file(char *filename)
  121. {
  122. int ret;
  123. const AVCodec *decoder = NULL;
  124. AVStream *video = NULL;
  125. if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
  126. fprintf(stderr, "Cannot open input file '%s', Error code: %s\n",
  127. filename, av_err2str(ret));
  128. return ret;
  129. }
  130. if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
  131. fprintf(stderr, "Cannot find input stream information. Error code: %s\n",
  132. av_err2str(ret));
  133. return ret;
  134. }
  135. ret = av_find_best_stream(ifmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
  136. if (ret < 0) {
  137. fprintf(stderr, "Cannot find a video stream in the input file. "
  138. "Error code: %s\n", av_err2str(ret));
  139. return ret;
  140. }
  141. video_stream = ret;
  142. video = ifmt_ctx->streams[video_stream];
  143. switch(video->codecpar->codec_id) {
  144. case AV_CODEC_ID_H264:
  145. decoder = avcodec_find_decoder_by_name("h264_qsv");
  146. break;
  147. case AV_CODEC_ID_HEVC:
  148. decoder = avcodec_find_decoder_by_name("hevc_qsv");
  149. break;
  150. case AV_CODEC_ID_VP9:
  151. decoder = avcodec_find_decoder_by_name("vp9_qsv");
  152. break;
  153. case AV_CODEC_ID_VP8:
  154. decoder = avcodec_find_decoder_by_name("vp8_qsv");
  155. break;
  156. case AV_CODEC_ID_AV1:
  157. decoder = avcodec_find_decoder_by_name("av1_qsv");
  158. break;
  159. case AV_CODEC_ID_MPEG2VIDEO:
  160. decoder = avcodec_find_decoder_by_name("mpeg2_qsv");
  161. break;
  162. case AV_CODEC_ID_MJPEG:
  163. decoder = avcodec_find_decoder_by_name("mjpeg_qsv");
  164. break;
  165. default:
  166. fprintf(stderr, "Codec is not supportted by qsv\n");
  167. return AVERROR(ENAVAIL);
  168. }
  169. if (!(decoder_ctx = avcodec_alloc_context3(decoder)))
  170. return AVERROR(ENOMEM);
  171. if ((ret = avcodec_parameters_to_context(decoder_ctx, video->codecpar)) < 0) {
  172. fprintf(stderr, "avcodec_parameters_to_context error. Error code: %s\n",
  173. av_err2str(ret));
  174. return ret;
  175. }
  176. decoder_ctx->framerate = av_guess_frame_rate(ifmt_ctx, video, NULL);
  177. decoder_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
  178. if (!decoder_ctx->hw_device_ctx) {
  179. fprintf(stderr, "A hardware device reference create failed.\n");
  180. return AVERROR(ENOMEM);
  181. }
  182. decoder_ctx->get_format = get_format;
  183. decoder_ctx->pkt_timebase = video->time_base;
  184. if ((ret = avcodec_open2(decoder_ctx, decoder, NULL)) < 0)
  185. fprintf(stderr, "Failed to open codec for decoding. Error code: %s\n",
  186. av_err2str(ret));
  187. return ret;
  188. }
  189. static int encode_write(AVPacket *enc_pkt, AVFrame *frame)
  190. {
  191. int ret = 0;
  192. av_packet_unref(enc_pkt);
  193. if((ret = dynamic_set_parameter(encoder_ctx)) < 0) {
  194. fprintf(stderr, "Failed to set dynamic parameter. Error code: %s\n",
  195. av_err2str(ret));
  196. goto end;
  197. }
  198. if ((ret = avcodec_send_frame(encoder_ctx, frame)) < 0) {
  199. fprintf(stderr, "Error during encoding. Error code: %s\n", av_err2str(ret));
  200. goto end;
  201. }
  202. while (1) {
  203. if (ret = avcodec_receive_packet(encoder_ctx, enc_pkt))
  204. break;
  205. enc_pkt->stream_index = 0;
  206. av_packet_rescale_ts(enc_pkt, encoder_ctx->time_base,
  207. ofmt_ctx->streams[0]->time_base);
  208. if ((ret = av_interleaved_write_frame(ofmt_ctx, enc_pkt)) < 0) {
  209. fprintf(stderr, "Error during writing data to output file. "
  210. "Error code: %s\n", av_err2str(ret));
  211. return ret;
  212. }
  213. }
  214. end:
  215. if (ret == AVERROR_EOF)
  216. return 0;
  217. ret = ((ret == AVERROR(EAGAIN)) ? 0:-1);
  218. return ret;
  219. }
  220. static int dec_enc(AVPacket *pkt, const AVCodec *enc_codec, char *optstr)
  221. {
  222. AVFrame *frame;
  223. int ret = 0;
  224. ret = avcodec_send_packet(decoder_ctx, pkt);
  225. if (ret < 0) {
  226. fprintf(stderr, "Error during decoding. Error code: %s\n", av_err2str(ret));
  227. return ret;
  228. }
  229. while (ret >= 0) {
  230. if (!(frame = av_frame_alloc()))
  231. return AVERROR(ENOMEM);
  232. ret = avcodec_receive_frame(decoder_ctx, frame);
  233. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  234. av_frame_free(&frame);
  235. return 0;
  236. } else if (ret < 0) {
  237. fprintf(stderr, "Error while decoding. Error code: %s\n", av_err2str(ret));
  238. goto fail;
  239. }
  240. if (!encoder_ctx->hw_frames_ctx) {
  241. AVDictionaryEntry *e = NULL;
  242. AVDictionary *opts = NULL;
  243. AVStream *ost;
  244. /* we need to ref hw_frames_ctx of decoder to initialize encoder's codec.
  245. Only after we get a decoded frame, can we obtain its hw_frames_ctx */
  246. encoder_ctx->hw_frames_ctx = av_buffer_ref(decoder_ctx->hw_frames_ctx);
  247. if (!encoder_ctx->hw_frames_ctx) {
  248. ret = AVERROR(ENOMEM);
  249. goto fail;
  250. }
  251. /* set AVCodecContext Parameters for encoder, here we keep them stay
  252. * the same as decoder.
  253. */
  254. encoder_ctx->time_base = av_inv_q(decoder_ctx->framerate);
  255. encoder_ctx->pix_fmt = AV_PIX_FMT_QSV;
  256. encoder_ctx->width = decoder_ctx->width;
  257. encoder_ctx->height = decoder_ctx->height;
  258. if ((ret = str_to_dict(optstr, &opts)) < 0) {
  259. fprintf(stderr, "Failed to set encoding parameter.\n");
  260. goto fail;
  261. }
  262. /* There is no "framerate" option in commom option list. Use "-r" to
  263. * set framerate, which is compatible with ffmpeg commandline. The
  264. * video is assumed to be average frame rate, so set time_base to
  265. * 1/framerate. */
  266. e = av_dict_get(opts, "r", NULL, 0);
  267. if (e) {
  268. encoder_ctx->framerate = av_d2q(atof(e->value), INT_MAX);
  269. encoder_ctx->time_base = av_inv_q(encoder_ctx->framerate);
  270. }
  271. if ((ret = avcodec_open2(encoder_ctx, enc_codec, &opts)) < 0) {
  272. fprintf(stderr, "Failed to open encode codec. Error code: %s\n",
  273. av_err2str(ret));
  274. av_dict_free(&opts);
  275. goto fail;
  276. }
  277. av_dict_free(&opts);
  278. if (!(ost = avformat_new_stream(ofmt_ctx, enc_codec))) {
  279. fprintf(stderr, "Failed to allocate stream for output format.\n");
  280. ret = AVERROR(ENOMEM);
  281. goto fail;
  282. }
  283. ost->time_base = encoder_ctx->time_base;
  284. ret = avcodec_parameters_from_context(ost->codecpar, encoder_ctx);
  285. if (ret < 0) {
  286. fprintf(stderr, "Failed to copy the stream parameters. "
  287. "Error code: %s\n", av_err2str(ret));
  288. goto fail;
  289. }
  290. /* write the stream header */
  291. if ((ret = avformat_write_header(ofmt_ctx, NULL)) < 0) {
  292. fprintf(stderr, "Error while writing stream header. "
  293. "Error code: %s\n", av_err2str(ret));
  294. goto fail;
  295. }
  296. }
  297. frame->pts = av_rescale_q(frame->pts, decoder_ctx->pkt_timebase,
  298. encoder_ctx->time_base);
  299. if ((ret = encode_write(pkt, frame)) < 0)
  300. fprintf(stderr, "Error during encoding and writing.\n");
  301. fail:
  302. av_frame_free(&frame);
  303. }
  304. return ret;
  305. }
  306. int main(int argc, char **argv)
  307. {
  308. const AVCodec *enc_codec;
  309. int ret = 0;
  310. AVPacket *dec_pkt = NULL;
  311. if (argc < 5 || (argc - 5) % 2) {
  312. av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <encoder> <output file>"
  313. " <\"encoding option set 0\"> [<frame_number> <\"encoding options set 1\">]...\n", argv[0]);
  314. return 1;
  315. }
  316. setting_number = (argc - 5) / 2;
  317. dynamic_setting = av_malloc(setting_number * sizeof(*dynamic_setting));
  318. current_setting_number = 0;
  319. for (int i = 0; i < setting_number; i++) {
  320. dynamic_setting[i].frame_number = atoi(argv[i*2 + 5]);
  321. dynamic_setting[i].optstr = argv[i*2 + 6];
  322. }
  323. ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_QSV, NULL, NULL, 0);
  324. if (ret < 0) {
  325. fprintf(stderr, "Failed to create a QSV device. Error code: %s\n", av_err2str(ret));
  326. goto end;
  327. }
  328. dec_pkt = av_packet_alloc();
  329. if (!dec_pkt) {
  330. fprintf(stderr, "Failed to allocate decode packet\n");
  331. goto end;
  332. }
  333. if ((ret = open_input_file(argv[1])) < 0)
  334. goto end;
  335. if (!(enc_codec = avcodec_find_encoder_by_name(argv[2]))) {
  336. fprintf(stderr, "Could not find encoder '%s'\n", argv[2]);
  337. ret = -1;
  338. goto end;
  339. }
  340. if ((ret = (avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, argv[3]))) < 0) {
  341. fprintf(stderr, "Failed to deduce output format from file extension. Error code: "
  342. "%s\n", av_err2str(ret));
  343. goto end;
  344. }
  345. if (!(encoder_ctx = avcodec_alloc_context3(enc_codec))) {
  346. ret = AVERROR(ENOMEM);
  347. goto end;
  348. }
  349. ret = avio_open(&ofmt_ctx->pb, argv[3], AVIO_FLAG_WRITE);
  350. if (ret < 0) {
  351. fprintf(stderr, "Cannot open output file. "
  352. "Error code: %s\n", av_err2str(ret));
  353. goto end;
  354. }
  355. /* read all packets and only transcoding video */
  356. while (ret >= 0) {
  357. if ((ret = av_read_frame(ifmt_ctx, dec_pkt)) < 0)
  358. break;
  359. if (video_stream == dec_pkt->stream_index)
  360. ret = dec_enc(dec_pkt, enc_codec, argv[4]);
  361. av_packet_unref(dec_pkt);
  362. }
  363. /* flush decoder */
  364. av_packet_unref(dec_pkt);
  365. if ((ret = dec_enc(dec_pkt, enc_codec, argv[4])) < 0) {
  366. fprintf(stderr, "Failed to flush decoder %s\n", av_err2str(ret));
  367. goto end;
  368. }
  369. /* flush encoder */
  370. if ((ret = encode_write(dec_pkt, NULL)) < 0) {
  371. fprintf(stderr, "Failed to flush encoder %s\n", av_err2str(ret));
  372. goto end;
  373. }
  374. /* write the trailer for output stream */
  375. if ((ret = av_write_trailer(ofmt_ctx)) < 0)
  376. fprintf(stderr, "Failed to write trailer %s\n", av_err2str(ret));
  377. end:
  378. avformat_close_input(&ifmt_ctx);
  379. avformat_close_input(&ofmt_ctx);
  380. avcodec_free_context(&decoder_ctx);
  381. avcodec_free_context(&encoder_ctx);
  382. av_buffer_unref(&hw_device_ctx);
  383. av_packet_free(&dec_pkt);
  384. av_freep(&dynamic_setting);
  385. return ret;
  386. }