]> git.sesse.net Git - x264/blob - input/avs.c
Bump dates to 2015
[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     FAIL_IF_ERROR( !x264_is_regular_file( fh ), "AVS input is incompatible with non-regular file `%s'\n", psz_filename );
179     fclose( fh );
180
181     avs_hnd_t *h = malloc( sizeof(avs_hnd_t) );
182     if( !h )
183         return -1;
184     FAIL_IF_ERROR( x264_avs_load_library( h ), "failed to load avisynth\n" )
185     h->env = h->func.avs_create_script_environment( AVS_INTERFACE_25 );
186     if( h->func.avs_get_error )
187     {
188         const char *error = h->func.avs_get_error( h->env );
189         FAIL_IF_ERROR( error, "%s\n", error );
190     }
191     float avs_version = get_avs_version( h );
192     if( avs_version <= 0 )
193         return -1;
194     x264_cli_log( "avs", X264_LOG_DEBUG, "using avisynth version %.2f\n", avs_version );
195
196 #ifdef _WIN32
197     /* Avisynth doesn't support Unicode filenames. */
198     char ansi_filename[MAX_PATH];
199     FAIL_IF_ERROR( !x264_ansi_filename( psz_filename, ansi_filename, MAX_PATH, 0 ), "invalid ansi filename\n" );
200     AVS_Value arg = avs_new_value_string( ansi_filename );
201 #else
202     AVS_Value arg = avs_new_value_string( psz_filename );
203 #endif
204
205     AVS_Value res;
206     char *filename_ext = get_filename_extension( psz_filename );
207
208     if( !strcasecmp( filename_ext, "avs" ) )
209     {
210         res = h->func.avs_invoke( h->env, "Import", arg, NULL );
211         FAIL_IF_ERROR( avs_is_error( res ), "%s\n", avs_as_string( res ) )
212         /* check if the user is using a multi-threaded script and apply distributor if necessary.
213            adapted from avisynth's vfw interface */
214         AVS_Value mt_test = h->func.avs_invoke( h->env, "GetMTMode", avs_new_value_bool( 0 ), NULL );
215         int mt_mode = avs_is_int( mt_test ) ? avs_as_int( mt_test ) : 0;
216         h->func.avs_release_value( mt_test );
217         if( mt_mode > 0 && mt_mode < 5 )
218         {
219             AVS_Value temp = h->func.avs_invoke( h->env, "Distributor", res, NULL );
220             h->func.avs_release_value( res );
221             res = temp;
222         }
223     }
224     else /* non script file */
225     {
226         /* cycle through known source filters to find one that works */
227         const char *filter[AVS_MAX_SEQUENCE+1] = { 0 };
228         avs_build_filter_sequence( filename_ext, filter );
229         int i;
230         for( i = 0; filter[i]; i++ )
231         {
232             x264_cli_log( "avs", X264_LOG_INFO, "trying %s... ", filter[i] );
233             if( !h->func.avs_function_exists( h->env, filter[i] ) )
234             {
235                 x264_cli_printf( X264_LOG_INFO, "not found\n" );
236                 continue;
237             }
238             if( !strncasecmp( filter[i], "FFmpegSource", 12 ) )
239             {
240                 x264_cli_printf( X264_LOG_INFO, "indexing... " );
241                 fflush( stderr );
242             }
243             res = h->func.avs_invoke( h->env, filter[i], arg, NULL );
244             if( !avs_is_error( res ) )
245             {
246                 x264_cli_printf( X264_LOG_INFO, "succeeded\n" );
247                 break;
248             }
249             x264_cli_printf( X264_LOG_INFO, "failed\n" );
250         }
251         FAIL_IF_ERROR( !filter[i], "unable to find source filter to open `%s'\n", psz_filename )
252     }
253     FAIL_IF_ERROR( !avs_is_clip( res ), "`%s' didn't return a video clip\n", psz_filename )
254     h->clip = h->func.avs_take_clip( res, h->env );
255     const AVS_VideoInfo *vi = h->func.avs_get_video_info( h->clip );
256     FAIL_IF_ERROR( !avs_has_video( vi ), "`%s' has no video data\n", psz_filename )
257     /* if the clip is made of fields instead of frames, call weave to make them frames */
258     if( avs_is_field_based( vi ) )
259     {
260         x264_cli_log( "avs", X264_LOG_WARNING, "detected fieldbased (separated) input, weaving to frames\n" );
261         AVS_Value tmp = h->func.avs_invoke( h->env, "Weave", res, NULL );
262         FAIL_IF_ERROR( avs_is_error( tmp ), "couldn't weave fields into frames\n" )
263         res = update_clip( h, &vi, tmp, res );
264         info->interlaced = 1;
265         info->tff = avs_is_tff( vi );
266     }
267 #if !HAVE_SWSCALE
268     /* if swscale is not available, convert the CSP if necessary */
269     FAIL_IF_ERROR( avs_version < 2.6f && (opt->output_csp == X264_CSP_I422 || opt->output_csp == X264_CSP_I444),
270                    "avisynth >= 2.6 is required for i422/i444 output\n" )
271     if( (opt->output_csp == X264_CSP_I420 && !avs_is_yv12( vi )) || (opt->output_csp == X264_CSP_I422 && !avs_is_yv16( vi )) ||
272         (opt->output_csp == X264_CSP_I444 && !avs_is_yv24( vi )) || (opt->output_csp == X264_CSP_RGB && !avs_is_rgb( vi )) )
273     {
274
275         const char *csp = opt->output_csp == X264_CSP_I420 ? "YV12" :
276                           opt->output_csp == X264_CSP_I422 ? "YV16" :
277                           opt->output_csp == X264_CSP_I444 ? "YV24" : "RGB";
278         x264_cli_log( "avs", X264_LOG_WARNING, "converting input clip to %s\n", csp );
279         FAIL_IF_ERROR( opt->output_csp < X264_CSP_I444 && (vi->width&1),
280                        "input clip width not divisible by 2 (%dx%d)\n", vi->width, vi->height )
281         FAIL_IF_ERROR( opt->output_csp == X264_CSP_I420 && info->interlaced && (vi->height&3),
282                        "input clip height not divisible by 4 (%dx%d)\n", vi->width, vi->height )
283         FAIL_IF_ERROR( (opt->output_csp == X264_CSP_I420 || info->interlaced) && (vi->height&1),
284                        "input clip height not divisible by 2 (%dx%d)\n", vi->width, vi->height )
285         char conv_func[14] = { "ConvertTo" };
286         strcat( conv_func, csp );
287         char matrix[7] = "";
288         int arg_count = 2;
289         /* if doing a rgb <-> yuv conversion then range is handled via 'matrix'. though it's only supported in 2.56+ */
290         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 ))) )
291         {
292             // if converting from yuv, then we specify the matrix for the input, otherwise use the output's.
293             int use_pc_matrix = avs_is_yuv( vi ) ? opt->input_range == RANGE_PC : opt->output_range == RANGE_PC;
294             strcpy( matrix, use_pc_matrix ? "PC." : "Rec" );
295             strcat( matrix, "601" ); /* 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, 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 )
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 };