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.

422 lines
16KB

  1. /*
  2. * Copyright (c) 2018 Sergey Lavrushkin
  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. /**
  21. * @file
  22. * Filter implementing image super-resolution using deep convolutional networks.
  23. * https://arxiv.org/abs/1501.00092
  24. */
  25. #include "avfilter.h"
  26. #include "formats.h"
  27. #include "internal.h"
  28. #include "libavutil/opt.h"
  29. #include "vf_srcnn.h"
  30. #include "libavformat/avio.h"
  31. typedef struct Convolution
  32. {
  33. double* kernel;
  34. double* biases;
  35. int32_t size, input_channels, output_channels;
  36. } Convolution;
  37. typedef struct SRCNNContext {
  38. const AVClass *class;
  39. /// SRCNN convolutions
  40. struct Convolution conv1, conv2, conv3;
  41. /// Path to binary file with kernels specifications
  42. char* config_file_path;
  43. /// Buffers for network input/output and feature maps
  44. double* input_output_buf;
  45. double* conv1_buf;
  46. double* conv2_buf;
  47. } SRCNNContext;
  48. #define OFFSET(x) offsetof(SRCNNContext, x)
  49. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
  50. static const AVOption srcnn_options[] = {
  51. { "config_file", "path to configuration file with network parameters", OFFSET(config_file_path), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
  52. { NULL }
  53. };
  54. AVFILTER_DEFINE_CLASS(srcnn);
  55. #define CHECK_FILE_SIZE(file_size, srcnn_size, avio_context) if (srcnn_size > file_size){ \
  56. av_log(context, AV_LOG_ERROR, "error reading configuration file\n");\
  57. avio_closep(&avio_context); \
  58. return AVERROR(EIO); \
  59. }
  60. #define CHECK_ALLOCATION(call, end_call) if (call){ \
  61. av_log(context, AV_LOG_ERROR, "could not allocate memory for convolutions\n"); \
  62. end_call; \
  63. return AVERROR(ENOMEM); \
  64. }
  65. static int allocate_read_conv_data(Convolution* conv, AVIOContext* config_file_context)
  66. {
  67. int32_t kernel_size = conv->output_channels * conv->size * conv->size * conv->input_channels;
  68. int32_t i;
  69. conv->kernel = av_malloc(kernel_size * sizeof(double));
  70. if (!conv->kernel){
  71. return AVERROR(ENOMEM);
  72. }
  73. for (i = 0; i < kernel_size; ++i){
  74. conv->kernel[i] = av_int2double(avio_rl64(config_file_context));
  75. }
  76. conv->biases = av_malloc(conv->output_channels * sizeof(double));
  77. if (!conv->biases){
  78. return AVERROR(ENOMEM);
  79. }
  80. for (i = 0; i < conv->output_channels; ++i){
  81. conv->biases[i] = av_int2double(avio_rl64(config_file_context));
  82. }
  83. return 0;
  84. }
  85. static int allocate_copy_conv_data(Convolution* conv, const double* kernel, const double* biases)
  86. {
  87. int32_t kernel_size = conv->output_channels * conv->size * conv->size * conv->input_channels;
  88. conv->kernel = av_malloc(kernel_size * sizeof(double));
  89. if (!conv->kernel){
  90. return AVERROR(ENOMEM);
  91. }
  92. memcpy(conv->kernel, kernel, kernel_size * sizeof(double));
  93. conv->biases = av_malloc(conv->output_channels * sizeof(double));
  94. if (!conv->kernel){
  95. return AVERROR(ENOMEM);
  96. }
  97. memcpy(conv->biases, biases, conv->output_channels * sizeof(double));
  98. return 0;
  99. }
  100. static av_cold int init(AVFilterContext* context)
  101. {
  102. SRCNNContext *srcnn_context = context->priv;
  103. AVIOContext* config_file_context;
  104. int64_t file_size, srcnn_size;
  105. /// Check specified confguration file name and read network weights from it
  106. if (!srcnn_context->config_file_path){
  107. av_log(context, AV_LOG_INFO, "configuration file for network was not specified, using default weights for x2 upsampling\n");
  108. /// Create convolution kernels and copy default weights
  109. srcnn_context->conv1.input_channels = 1;
  110. srcnn_context->conv1.output_channels = 64;
  111. srcnn_context->conv1.size = 9;
  112. CHECK_ALLOCATION(allocate_copy_conv_data(&srcnn_context->conv1, conv1_kernel, conv1_biases), )
  113. srcnn_context->conv2.input_channels = 64;
  114. srcnn_context->conv2.output_channels = 32;
  115. srcnn_context->conv2.size = 1;
  116. CHECK_ALLOCATION(allocate_copy_conv_data(&srcnn_context->conv2, conv2_kernel, conv2_biases), )
  117. srcnn_context->conv3.input_channels = 32;
  118. srcnn_context->conv3.output_channels = 1;
  119. srcnn_context->conv3.size = 5;
  120. CHECK_ALLOCATION(allocate_copy_conv_data(&srcnn_context->conv3, conv3_kernel, conv3_biases), )
  121. }
  122. else if (avio_check(srcnn_context->config_file_path, AVIO_FLAG_READ) > 0){
  123. if (avio_open(&config_file_context, srcnn_context->config_file_path, AVIO_FLAG_READ) < 0){
  124. av_log(context, AV_LOG_ERROR, "failed to open configuration file\n");
  125. return AVERROR(EIO);
  126. }
  127. file_size = avio_size(config_file_context);
  128. /// Create convolution kernels and read weights from file
  129. srcnn_context->conv1.input_channels = 1;
  130. srcnn_context->conv1.size = (int32_t)avio_rl32(config_file_context);
  131. srcnn_context->conv1.output_channels = (int32_t)avio_rl32(config_file_context);
  132. srcnn_size = 8 + (srcnn_context->conv1.output_channels * srcnn_context->conv1.size *
  133. srcnn_context->conv1.size * srcnn_context->conv1.input_channels +
  134. srcnn_context->conv1.output_channels << 3);
  135. CHECK_FILE_SIZE(file_size, srcnn_size, config_file_context)
  136. CHECK_ALLOCATION(allocate_read_conv_data(&srcnn_context->conv1, config_file_context), avio_closep(&config_file_context))
  137. srcnn_context->conv2.input_channels = (int32_t)avio_rl32(config_file_context);
  138. srcnn_context->conv2.size = (int32_t)avio_rl32(config_file_context);
  139. srcnn_context->conv2.output_channels = (int32_t)avio_rl32(config_file_context);
  140. srcnn_size += 12 + (srcnn_context->conv2.output_channels * srcnn_context->conv2.size *
  141. srcnn_context->conv2.size * srcnn_context->conv2.input_channels +
  142. srcnn_context->conv2.output_channels << 3);
  143. CHECK_FILE_SIZE(file_size, srcnn_size, config_file_context)
  144. CHECK_ALLOCATION(allocate_read_conv_data(&srcnn_context->conv2, config_file_context), avio_closep(&config_file_context))
  145. srcnn_context->conv3.input_channels = (int32_t)avio_rl32(config_file_context);
  146. srcnn_context->conv3.size = (int32_t)avio_rl32(config_file_context);
  147. srcnn_context->conv3.output_channels = 1;
  148. srcnn_size += 8 + (srcnn_context->conv3.output_channels * srcnn_context->conv3.size *
  149. srcnn_context->conv3.size * srcnn_context->conv3.input_channels
  150. + srcnn_context->conv3.output_channels << 3);
  151. if (file_size != srcnn_size){
  152. av_log(context, AV_LOG_ERROR, "error reading configuration file\n");
  153. avio_closep(&config_file_context);
  154. return AVERROR(EIO);
  155. }
  156. CHECK_ALLOCATION(allocate_read_conv_data(&srcnn_context->conv3, config_file_context), avio_closep(&config_file_context))
  157. avio_closep(&config_file_context);
  158. }
  159. else{
  160. av_log(context, AV_LOG_ERROR, "specified configuration file does not exist or not readable\n");
  161. return AVERROR(EIO);
  162. }
  163. return 0;
  164. }
  165. static int query_formats(AVFilterContext* context)
  166. {
  167. const enum AVPixelFormat pixel_formats[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
  168. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_GRAY8,
  169. AV_PIX_FMT_NONE};
  170. AVFilterFormats *formats_list;
  171. formats_list = ff_make_format_list(pixel_formats);
  172. if (!formats_list){
  173. av_log(context, AV_LOG_ERROR, "could not create formats list\n");
  174. return AVERROR(ENOMEM);
  175. }
  176. return ff_set_common_formats(context, formats_list);
  177. }
  178. static int config_props(AVFilterLink* inlink)
  179. {
  180. AVFilterContext *context = inlink->dst;
  181. SRCNNContext *srcnn_context = context->priv;
  182. int min_dim;
  183. /// Check if input data width or height is too low
  184. min_dim = FFMIN(inlink->w, inlink->h);
  185. if (min_dim <= srcnn_context->conv1.size >> 1 || min_dim <= srcnn_context->conv2.size >> 1 || min_dim <= srcnn_context->conv3.size >> 1){
  186. av_log(context, AV_LOG_ERROR, "input width or height is too low\n");
  187. return AVERROR(EIO);
  188. }
  189. /// Allocate network buffers
  190. srcnn_context->input_output_buf = av_malloc(inlink->h * inlink->w * sizeof(double));
  191. srcnn_context->conv1_buf = av_malloc(inlink->h * inlink->w * srcnn_context->conv1.output_channels * sizeof(double));
  192. srcnn_context->conv2_buf = av_malloc(inlink->h * inlink->w * srcnn_context->conv2.output_channels * sizeof(double));
  193. if (!srcnn_context->input_output_buf || !srcnn_context->conv1_buf || !srcnn_context->conv2_buf){
  194. av_log(context, AV_LOG_ERROR, "could not allocate memory for srcnn buffers\n");
  195. return AVERROR(ENOMEM);
  196. }
  197. return 0;
  198. }
  199. typedef struct ThreadData{
  200. uint8_t* out;
  201. int out_linesize, height, width;
  202. } ThreadData;
  203. typedef struct ConvThreadData
  204. {
  205. const Convolution* conv;
  206. const double* input;
  207. double* output;
  208. int height, width;
  209. } ConvThreadData;
  210. /// Convert uint8 data to double and scale it to use in network
  211. static int uint8_to_double(AVFilterContext* context, void* arg, int jobnr, int nb_jobs)
  212. {
  213. SRCNNContext* srcnn_context = context->priv;
  214. const ThreadData* td = arg;
  215. const int slice_start = (td->height * jobnr ) / nb_jobs;
  216. const int slice_end = (td->height * (jobnr + 1)) / nb_jobs;
  217. const uint8_t* src = td->out + slice_start * td->out_linesize;
  218. double* dst = srcnn_context->input_output_buf + slice_start * td->width;
  219. int y, x;
  220. for (y = slice_start; y < slice_end; ++y){
  221. for (x = 0; x < td->width; ++x){
  222. dst[x] = (double)src[x] / 255.0;
  223. }
  224. src += td->out_linesize;
  225. dst += td->width;
  226. }
  227. return 0;
  228. }
  229. /// Convert double data from network to uint8 and scale it to output as filter result
  230. static int double_to_uint8(AVFilterContext* context, void* arg, int jobnr, int nb_jobs)
  231. {
  232. SRCNNContext* srcnn_context = context->priv;
  233. const ThreadData* td = arg;
  234. const int slice_start = (td->height * jobnr ) / nb_jobs;
  235. const int slice_end = (td->height * (jobnr + 1)) / nb_jobs;
  236. const double* src = srcnn_context->input_output_buf + slice_start * td->width;
  237. uint8_t* dst = td->out + slice_start * td->out_linesize;
  238. int y, x;
  239. for (y = slice_start; y < slice_end; ++y){
  240. for (x = 0; x < td->width; ++x){
  241. dst[x] = (uint8_t)(255.0 * FFMIN(src[x], 1.0));
  242. }
  243. src += td->width;
  244. dst += td->out_linesize;
  245. }
  246. return 0;
  247. }
  248. #define CLAMP_TO_EDGE(x, w) ((x) < 0 ? 0 : ((x) >= (w) ? (w - 1) : (x)))
  249. static int convolve(AVFilterContext* context, void* arg, int jobnr, int nb_jobs)
  250. {
  251. const ConvThreadData* td = arg;
  252. const int slice_start = (td->height * jobnr ) / nb_jobs;
  253. const int slice_end = (td->height * (jobnr + 1)) / nb_jobs;
  254. const double* src = td->input;
  255. double* dst = td->output + slice_start * td->width * td->conv->output_channels;
  256. int y, x;
  257. int32_t n_filter, ch, kernel_y, kernel_x;
  258. int32_t radius = td->conv->size >> 1;
  259. int src_linesize = td->width * td->conv->input_channels;
  260. int filter_linesize = td->conv->size * td->conv->input_channels;
  261. int filter_size = td->conv->size * filter_linesize;
  262. for (y = slice_start; y < slice_end; ++y){
  263. for (x = 0; x < td->width; ++x){
  264. for (n_filter = 0; n_filter < td->conv->output_channels; ++n_filter){
  265. dst[n_filter] = td->conv->biases[n_filter];
  266. for (ch = 0; ch < td->conv->input_channels; ++ch){
  267. for (kernel_y = 0; kernel_y < td->conv->size; ++kernel_y){
  268. for (kernel_x = 0; kernel_x < td->conv->size; ++kernel_x){
  269. dst[n_filter] += src[CLAMP_TO_EDGE(y + kernel_y - radius, td->height) * src_linesize +
  270. CLAMP_TO_EDGE(x + kernel_x - radius, td->width) * td->conv->input_channels + ch] *
  271. td->conv->kernel[n_filter * filter_size + kernel_y * filter_linesize +
  272. kernel_x * td->conv->input_channels + ch];
  273. }
  274. }
  275. }
  276. dst[n_filter] = FFMAX(dst[n_filter], 0.0);
  277. }
  278. dst += td->conv->output_channels;
  279. }
  280. }
  281. return 0;
  282. }
  283. static int filter_frame(AVFilterLink* inlink, AVFrame* in)
  284. {
  285. AVFilterContext* context = inlink->dst;
  286. SRCNNContext* srcnn_context = context->priv;
  287. AVFilterLink* outlink = context->outputs[0];
  288. AVFrame* out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  289. ThreadData td;
  290. ConvThreadData ctd;
  291. int nb_threads;
  292. if (!out){
  293. av_log(context, AV_LOG_ERROR, "could not allocate memory for output frame\n");
  294. av_frame_free(&in);
  295. return AVERROR(ENOMEM);
  296. }
  297. av_frame_copy_props(out, in);
  298. av_frame_copy(out, in);
  299. av_frame_free(&in);
  300. td.out = out->data[0];
  301. td.out_linesize = out->linesize[0];
  302. td.height = ctd.height = out->height;
  303. td.width = ctd.width = out->width;
  304. nb_threads = ff_filter_get_nb_threads(context);
  305. context->internal->execute(context, uint8_to_double, &td, NULL, FFMIN(td.height, nb_threads));
  306. ctd.conv = &srcnn_context->conv1;
  307. ctd.input = srcnn_context->input_output_buf;
  308. ctd.output = srcnn_context->conv1_buf;
  309. context->internal->execute(context, convolve, &ctd, NULL, FFMIN(ctd.height, nb_threads));
  310. ctd.conv = &srcnn_context->conv2;
  311. ctd.input = srcnn_context->conv1_buf;
  312. ctd.output = srcnn_context->conv2_buf;
  313. context->internal->execute(context, convolve, &ctd, NULL, FFMIN(ctd.height, nb_threads));
  314. ctd.conv = &srcnn_context->conv3;
  315. ctd.input = srcnn_context->conv2_buf;
  316. ctd.output = srcnn_context->input_output_buf;
  317. context->internal->execute(context, convolve, &ctd, NULL, FFMIN(ctd.height, nb_threads));
  318. context->internal->execute(context, double_to_uint8, &td, NULL, FFMIN(td.height, nb_threads));
  319. return ff_filter_frame(outlink, out);
  320. }
  321. static av_cold void uninit(AVFilterContext* context)
  322. {
  323. SRCNNContext* srcnn_context = context->priv;
  324. /// Free convolution data
  325. av_freep(&srcnn_context->conv1.kernel);
  326. av_freep(&srcnn_context->conv1.biases);
  327. av_freep(&srcnn_context->conv2.kernel);
  328. av_freep(&srcnn_context->conv2.biases);
  329. av_freep(&srcnn_context->conv3.kernel);
  330. av_freep(&srcnn_context->conv3.kernel);
  331. /// Free network buffers
  332. av_freep(&srcnn_context->input_output_buf);
  333. av_freep(&srcnn_context->conv1_buf);
  334. av_freep(&srcnn_context->conv2_buf);
  335. }
  336. static const AVFilterPad srcnn_inputs[] = {
  337. {
  338. .name = "default",
  339. .type = AVMEDIA_TYPE_VIDEO,
  340. .config_props = config_props,
  341. .filter_frame = filter_frame,
  342. },
  343. { NULL }
  344. };
  345. static const AVFilterPad srcnn_outputs[] = {
  346. {
  347. .name = "default",
  348. .type = AVMEDIA_TYPE_VIDEO,
  349. },
  350. { NULL }
  351. };
  352. AVFilter ff_vf_srcnn = {
  353. .name = "srcnn",
  354. .description = NULL_IF_CONFIG_SMALL("Apply super resolution convolutional neural network to the input. Use bicubic upsamping with corresponding scaling factor before."),
  355. .priv_size = sizeof(SRCNNContext),
  356. .init = init,
  357. .uninit = uninit,
  358. .query_formats = query_formats,
  359. .inputs = srcnn_inputs,
  360. .outputs = srcnn_outputs,
  361. .priv_class = &srcnn_class,
  362. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
  363. };