qsv_transcode.c 15 KB

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