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