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.

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