]> git.sesse.net Git - x264/blob - input/avs.c
cli: Use memory-mapped input frames for yuv and y4m
[x264] / input / avs.c
1 /*****************************************************************************
2  * avs.c: avisynth input
3  *****************************************************************************
4  * Copyright (C) 2009-2015 x264 project
5  *
6  * Authors: Steven Walters <kemuri9@gmail.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
21  *
22  * This program is also available under a commercial proprietary license.
23  * For more information, contact us at licensing@x264.com.
24  *****************************************************************************/
25
26 #include "input.h"
27 #if USE_AVXSYNTH
28 #include <dlfcn.h>
29 #if SYS_MACOSX
30 #define avs_open() dlopen( "libavxsynth.dylib", RTLD_NOW )
31 #else
32 #define avs_open() dlopen( "libavxsynth.so", RTLD_NOW )
33 #endif
34 #define avs_close dlclose
35 #define avs_address dlsym
36 #else
37 #include <windows.h>
38 #define avs_open() LoadLibraryW( L"avisynth" )
39 #define avs_close FreeLibrary
40 #define avs_address GetProcAddress
41 #endif
42 #define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "avs", __VA_ARGS__ )
43
44 #define AVSC_NO_DECLSPEC
45 #undef EXTERN_C
46 #if USE_AVXSYNTH
47 #include "extras/avxsynth_c.h"
48 #else
49 #include "extras/avisynth_c.h"
50 #endif
51 #define AVSC_DECLARE_FUNC(name) name##_func name
52
53 /* AVS uses a versioned interface to control backwards compatibility */
54 /* YV12 support is required, which was added in 2.5 */
55 #define AVS_INTERFACE_25 2
56
57 #if HAVE_SWSCALE
58 #include <libavutil/pixfmt.h>
59 #endif
60
61 /* AvxSynth doesn't have yv24, yv16, yv411, or y8, so disable them. */
62 #if USE_AVXSYNTH
63 #define avs_is_yv24( vi ) 0
64 #define avs_is_yv16( vi ) 0
65 #define avs_is_yv411( vi ) 0
66 #define avs_is_y8( vi ) 0
67 #endif
68
69 /* maximum size of the sequence of filters to try on non script files */
70 #define AVS_MAX_SEQUENCE 5
71
72 #define LOAD_AVS_FUNC(name, continue_on_fail)\
73 {\
74     h->func.name = (void*)avs_address( h->library, #name );\
75     if( !continue_on_fail && !h->func.name )\
76         goto fail;\
77 }
78
79 typedef struct
80 {
81     AVS_Clip *clip;
82     AVS_ScriptEnvironment *env;
83     void *library;
84     int num_frames;
85     struct
86     {
87         AVSC_DECLARE_FUNC( avs_clip_get_error );
88         AVSC_DECLARE_FUNC( avs_create_script_environment );
89         AVSC_DECLARE_FUNC( avs_delete_script_environment );
90         AVSC_DECLARE_FUNC( avs_get_error );
91         AVSC_DECLARE_FUNC( avs_get_frame );
92         AVSC_DECLARE_FUNC( avs_get_video_info );
93         AVSC_DECLARE_FUNC( avs_function_exists );
94         AVSC_DECLARE_FUNC( avs_invoke );
95         AVSC_DECLARE_FUNC( avs_release_clip );
96         AVSC_DECLARE_FUNC( avs_release_value );
97         AVSC_DECLARE_FUNC( avs_release_video_frame );
98         AVSC_DECLARE_FUNC( avs_take_clip );
99     } func;
100 } avs_hnd_t;
101
102 /* load the library and functions we require from it */
103 static int x264_avs_load_library( avs_hnd_t *h )
104 {
105     h->library = avs_open();
106     if( !h->library )
107         return -1;
108     LOAD_AVS_FUNC( avs_clip_get_error, 0 );
109     LOAD_AVS_FUNC( avs_create_script_environment, 0 );
110     LOAD_AVS_FUNC( avs_delete_script_environment, 1 );
111     LOAD_AVS_FUNC( avs_get_error, 1 );
112     LOAD_AVS_FUNC( avs_get_frame, 0 );
113     LOAD_AVS_FUNC( avs_get_video_info, 0 );
114     LOAD_AVS_FUNC( avs_function_exists, 0 );
115     LOAD_AVS_FUNC( avs_invoke, 0 );
116     LOAD_AVS_FUNC( avs_release_clip, 0 );
117     LOAD_AVS_FUNC( avs_release_value, 0 );
118     LOAD_AVS_FUNC( avs_release_video_frame, 0 );
119     LOAD_AVS_FUNC( avs_take_clip, 0 );
120     return 0;
121 fail:
122     avs_close( h->library );
123     return -1;
124 }
125
126 /* generate a filter sequence to try based on the filename extension */
127 static void avs_build_filter_sequence( char *filename_ext, const char *filter[AVS_MAX_SEQUENCE+1] )
128 {
129     int i = 0;
130 #if USE_AVXSYNTH
131     const char *all_purpose[] = { "FFVideoSource", 0 };
132 #else
133     const char *all_purpose[] = { "FFmpegSource2", "DSS2", "DirectShowSource", 0 };
134     if( !strcasecmp( filename_ext, "avi" ) )
135         filter[i++] = "AVISource";
136     if( !strcasecmp( filename_ext, "d2v" ) )
137         filter[i++] = "MPEG2Source";
138     if( !strcasecmp( filename_ext, "dga" ) )
139         filter[i++] = "AVCSource";
140 #endif
141     for( int j = 0; all_purpose[j] && i < AVS_MAX_SEQUENCE; j++ )
142         filter[i++] = all_purpose[j];
143 }
144
145 static AVS_Value update_clip( avs_hnd_t *h, const AVS_VideoInfo **vi, AVS_Value res, AVS_Value release )
146 {
147     h->func.avs_release_clip( h->clip );
148     h->clip = h->func.avs_take_clip( res, h->env );
149     h->func.avs_release_value( release );
150     *vi = h->func.avs_get_video_info( h->clip );
151     return res;
152 }
153
154 static float get_avs_version( avs_hnd_t *h )
155 {
156 /* AvxSynth has its version defined starting at 4.0, even though it's based on
157    AviSynth 2.5.8. This is troublesome for get_avs_version and working around
158    the new colorspaces in 2.6.  So if AvxSynth is detected, explicitly define
159    the version as 2.58. */
160 #if USE_AVXSYNTH
161     return 2.58f;
162 #else
163     FAIL_IF_ERROR( !h->func.avs_function_exists( h->env, "VersionNumber" ), "VersionNumber does not exist\n" )
164     AVS_Value ver = h->func.avs_invoke( h->env, "VersionNumber", avs_new_value_array( NULL, 0 ), NULL );
165     FAIL_IF_ERROR( avs_is_error( ver ), "unable to determine avisynth version: %s\n", avs_as_error( ver ) )
166     FAIL_IF_ERROR( !avs_is_float( ver ), "VersionNumber did not return a float value\n" );
167     float ret = avs_as_float( ver );
168     h->func.avs_release_value( ver );
169     return ret;
170 #endif
171 }
172
173 static int open_file( char *psz_filename, hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt )
174 {
175     FILE *fh = x264_fopen( psz_filename, "r" );
176     if( !fh )
177         return -1;
178     int b_regular = x264_is_regular_file( fh );
179     fclose( fh );
180     FAIL_IF_ERROR( !b_regular, "AVS input is incompatible with non-regular file `%s'\n", psz_filename );
181
182     avs_hnd_t *h = malloc( sizeof(avs_hnd_t) );
183     if( !h )
184         return -1;
185     FAIL_IF_ERROR( x264_avs_load_library( h ), "failed to load avisynth\n" )
186     h->env = h->func.avs_create_script_environment( AVS_INTERFACE_25 );
187     if( h->func.avs_get_error )
188     {
189         const char *error = h->func.avs_get_error( h->env );
190         FAIL_IF_ERROR( error, "%s\n", error );
191     }
192     float avs_version = get_avs_version( h );
193     if( avs_version <= 0 )
194         return -1;
195     x264_cli_log( "avs", X264_LOG_DEBUG, "using avisynth version %.2f\n", avs_version );
196
197 #ifdef _WIN32
198     /* Avisynth doesn't support Unicode filenames. */
199     char ansi_filename[MAX_PATH];
200     FAIL_IF_ERROR( !x264_ansi_filename( psz_filename, ansi_filename, MAX_PATH, 0 ), "invalid ansi filename\n" );
201     AVS_Value arg = avs_new_value_string( ansi_filename );
202 #else
203     AVS_Value arg = avs_new_value_string( psz_filename );
204 #endif
205
206     AVS_Value res;
207     char *filename_ext = get_filename_extension( psz_filename );
208
209     if( !strcasecmp( filename_ext, "avs" ) )
210     {
211         res = h->func.avs_invoke( h->env, "Import", arg, NULL );
212         FAIL_IF_ERROR( avs_is_error( res ), "%s\n", avs_as_string( res ) )
213         /* check if the user is using a multi-threaded script and apply distributor if necessary.
214            adapted from avisynth's vfw interface */
215         AVS_Value mt_test = h->func.avs_invoke( h->env, "GetMTMode", avs_new_value_bool( 0 ), NULL );
216         int mt_mode = avs_is_int( mt_test ) ? avs_as_int( mt_test ) : 0;
217         h->func.avs_release_value( mt_test );
218         if( mt_mode > 0 && mt_mode < 5 )
219         {
220             AVS_Value temp = h->func.avs_invoke( h->env, "Distributor", res, NULL );
221             h->func.avs_release_value( res );
222             res = temp;
223         }
224     }
225     else /* non script file */
226     {
227         /* cycle through known source filters to find one that works */
228         const char *filter[AVS_MAX_SEQUENCE+1] = { 0 };
229         avs_build_filter_sequence( filename_ext, filter );
230         int i;
231         for( i = 0; filter[i]; i++ )
232         {
233             x264_cli_log( "avs", X264_LOG_INFO, "trying %s... ", filter[i] );
234             if( !h->func.avs_function_exists( h->env, filter[i] ) )
235             {
236                 x264_cli_printf( X264_LOG_INFO, "not found\n" );
237                 continue;
238             }
239             if( !strncasecmp( filter[i], "FFmpegSource", 12 ) )
240             {
241                 x264_cli_printf( X264_LOG_INFO, "indexing... " );
242                 fflush( stderr );
243             }
244             res = h->func.avs_invoke( h->env, filter[i], arg, NULL );
245             if( !avs_is_error( res ) )
246             {
247                 x264_cli_printf( X264_LOG_INFO, "succeeded\n" );
248                 break;
249             }
250             x264_cli_printf( X264_LOG_INFO, "failed\n" );
251         }
252         FAIL_IF_ERROR( !filter[i], "unable to find source filter to open `%s'\n", psz_filename )
253     }
254     FAIL_IF_ERROR( !avs_is_clip( res ), "`%s' didn't return a video clip\n", psz_filename )
255     h->clip = h->func.avs_take_clip( res, h->env );
256     const AVS_VideoInfo *vi = h->func.avs_get_video_info( h->clip );
257     FAIL_IF_ERROR( !avs_has_video( vi ), "`%s' has no video data\n", psz_filename )
258     /* if the clip is made of fields instead of frames, call weave to make them frames */
259     if( avs_is_field_based( vi ) )
260     {
261         x264_cli_log( "avs", X264_LOG_WARNING, "detected fieldbased (separated) input, weaving to frames\n" );
262         AVS_Value tmp = h->func.avs_invoke( h->env, "Weave", res, NULL );
263         FAIL_IF_ERROR( avs_is_error( tmp ), "couldn't weave fields into frames\n" )
264         res = update_clip( h, &vi, tmp, res );
265         info->interlaced = 1;
266         info->tff = avs_is_tff( vi );
267     }
268 #if !HAVE_SWSCALE
269     /* if swscale is not available, convert the CSP if necessary */
270     FAIL_IF_ERROR( avs_version < 2.6f && (opt->output_csp == X264_CSP_I422 || opt->output_csp == X264_CSP_I444),
271                    "avisynth >= 2.6 is required for i422/i444 output\n" )
272     if( (opt->output_csp == X264_CSP_I420 && !avs_is_yv12( vi )) || (opt->output_csp == X264_CSP_I422 && !avs_is_yv16( vi )) ||
273         (opt->output_csp == X264_CSP_I444 && !avs_is_yv24( vi )) || (opt->output_csp == X264_CSP_RGB && !avs_is_rgb( vi )) )
274     {
275
276         const char *csp = opt->output_csp == X264_CSP_I420 ? "YV12" :
277                           opt->output_csp == X264_CSP_I422 ? "YV16" :
278                           opt->output_csp == X264_CSP_I444 ? "YV24" : "RGB";
279         x264_cli_log( "avs", X264_LOG_WARNING, "converting input clip to %s\n", csp );
280         FAIL_IF_ERROR( opt->output_csp < X264_CSP_I444 && (vi->width&1),
281                        "input clip width not divisible by 2 (%dx%d)\n", vi->width, vi->height )
282         FAIL_IF_ERROR( opt->output_csp == X264_CSP_I420 && info->interlaced && (vi->height&3),
283                        "input clip height not divisible by 4 (%dx%d)\n", vi->width, vi->height )
284         FAIL_IF_ERROR( (opt->output_csp == X264_CSP_I420 || info->interlaced) && (vi->height&1),
285                        "input clip height not divisible by 2 (%dx%d)\n", vi->width, vi->height )
286         char conv_func[14];
287         snprintf( conv_func, sizeof(conv_func), "ConvertTo%s", csp );
288         char matrix[7] = "";
289         int arg_count = 2;
290         /* if doing a rgb <-> yuv conversion then range is handled via 'matrix'. though it's only supported in 2.56+ */
291         if( avs_version >= 2.56f && ((opt->output_csp == X264_CSP_RGB && avs_is_yuv( vi )) || (opt->output_csp != X264_CSP_RGB && avs_is_rgb( vi ))) )
292         {
293             // if converting from yuv, then we specify the matrix for the input, otherwise use the output's.
294             int use_pc_matrix = avs_is_yuv( vi ) ? opt->input_range == RANGE_PC : opt->output_range == RANGE_PC;
295             snprintf( matrix, sizeof(matrix), "%s601", use_pc_matrix ? "PC." : "Rec" ); /* FIXME: use correct coefficients */
296             arg_count++;
297             // notification that the input range has changed to the desired one
298             opt->input_range = opt->output_range;
299         }
300         const char *arg_name[] = { NULL, "interlaced", "matrix" };
301         AVS_Value arg_arr[3];
302         arg_arr[0] = res;
303         arg_arr[1] = avs_new_value_bool( info->interlaced );
304         arg_arr[2] = avs_new_value_string( matrix );
305         AVS_Value res2 = h->func.avs_invoke( h->env, conv_func, avs_new_value_array( arg_arr, arg_count ), arg_name );
306         FAIL_IF_ERROR( avs_is_error( res2 ), "couldn't convert input clip to %s\n", csp )
307         res = update_clip( h, &vi, res2, res );
308     }
309     /* if swscale is not available, change the range if necessary. This only applies to YUV-based CSPs however */
310     if( avs_is_yuv( vi ) && opt->output_range != RANGE_AUTO && ((opt->input_range == RANGE_PC) != opt->output_range) )
311     {
312         const char *levels = opt->output_range ? "TV->PC" : "PC->TV";
313         x264_cli_log( "avs", X264_LOG_WARNING, "performing %s conversion\n", levels );
314         AVS_Value arg_arr[2];
315         arg_arr[0] = res;
316         arg_arr[1] = avs_new_value_string( levels );
317         const char *arg_name[] = { NULL, "levels" };
318         AVS_Value res2 = h->func.avs_invoke( h->env, "ColorYUV", avs_new_value_array( arg_arr, 2 ), arg_name );
319         FAIL_IF_ERROR( avs_is_error( res2 ), "couldn't convert range: %s\n", avs_as_error( res2 ) )
320         res = update_clip( h, &vi, res2, res );
321         // notification that the input range has changed to the desired one
322         opt->input_range = opt->output_range;
323     }
324 #endif
325
326     h->func.avs_release_value( res );
327
328     info->width   = vi->width;
329     info->height  = vi->height;
330     info->fps_num = vi->fps_numerator;
331     info->fps_den = vi->fps_denominator;
332     h->num_frames = info->num_frames = vi->num_frames;
333     info->thread_safe = 1;
334     if( avs_is_rgb32( vi ) )
335         info->csp = X264_CSP_BGRA | X264_CSP_VFLIP;
336     else if( avs_is_rgb24( vi ) )
337         info->csp = X264_CSP_BGR | X264_CSP_VFLIP;
338     else if( avs_is_yv24( vi ) )
339         info->csp = X264_CSP_I444;
340     else if( avs_is_yv16( vi ) )
341         info->csp = X264_CSP_I422;
342     else if( avs_is_yv12( vi ) )
343         info->csp = X264_CSP_I420;
344 #if HAVE_SWSCALE
345     else if( avs_is_yuy2( vi ) )
346         info->csp = AV_PIX_FMT_YUYV422 | X264_CSP_OTHER;
347     else if( avs_is_yv411( vi ) )
348         info->csp = AV_PIX_FMT_YUV411P | X264_CSP_OTHER;
349     else if( avs_is_y8( vi ) )
350         info->csp = AV_PIX_FMT_GRAY8 | X264_CSP_OTHER;
351 #endif
352     else
353         info->csp = X264_CSP_NONE;
354     info->vfr = 0;
355
356     *p_handle = h;
357     return 0;
358 }
359
360 static int picture_alloc( cli_pic_t *pic, hnd_t handle, int csp, int width, int height )
361 {
362     if( x264_cli_pic_alloc( pic, X264_CSP_NONE, width, height ) )
363         return -1;
364     pic->img.csp = csp;
365     const x264_cli_csp_t *cli_csp = x264_cli_get_csp( csp );
366     if( cli_csp )
367         pic->img.planes = cli_csp->planes;
368 #if HAVE_SWSCALE
369     else if( csp == (AV_PIX_FMT_YUV411P | X264_CSP_OTHER) )
370         pic->img.planes = 3;
371     else
372         pic->img.planes = 1; //y8 and yuy2 are one plane
373 #endif
374     return 0;
375 }
376
377 static int read_frame( cli_pic_t *pic, hnd_t handle, int i_frame )
378 {
379     static const int plane[3] = { AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V };
380     avs_hnd_t *h = handle;
381     if( i_frame >= h->num_frames )
382         return -1;
383     AVS_VideoFrame *frm = pic->opaque = h->func.avs_get_frame( h->clip, i_frame );
384     const char *err = h->func.avs_clip_get_error( h->clip );
385     FAIL_IF_ERROR( err, "%s occurred while reading frame %d\n", err, i_frame )
386     for( int i = 0; i < pic->img.planes; i++ )
387     {
388         /* explicitly cast away the const attribute to avoid a warning */
389         pic->img.plane[i] = (uint8_t*)avs_get_read_ptr_p( frm, plane[i] );
390         pic->img.stride[i] = avs_get_pitch_p( frm, plane[i] );
391     }
392     return 0;
393 }
394
395 static int release_frame( cli_pic_t *pic, hnd_t handle )
396 {
397     avs_hnd_t *h = handle;
398     h->func.avs_release_video_frame( pic->opaque );
399     return 0;
400 }
401
402 static void picture_clean( cli_pic_t *pic, hnd_t handle )
403 {
404     memset( pic, 0, sizeof(cli_pic_t) );
405 }
406
407 static int close_file( hnd_t handle )
408 {
409     avs_hnd_t *h = handle;
410     h->func.avs_release_clip( h->clip );
411     if( h->func.avs_delete_script_environment )
412         h->func.avs_delete_script_environment( h->env );
413     avs_close( h->library );
414     free( h );
415     return 0;
416 }
417
418 const cli_input_t avs_input = { open_file, picture_alloc, read_frame, release_frame, picture_clean, close_file };