]> git.sesse.net Git - ffmpeg/blob - libavformat/avisynth.c
Merge commit '4ab496261b12e20ef293b7adca4fcaef1a67c538'
[ffmpeg] / libavformat / avisynth.c
1 /*
2  * AviSynth/AvxSynth support
3  * Copyright (c) 2012 AvxSynth Team
4  *
5  * This file is part of FFmpeg
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 #include "libavutil/internal.h"
22 #include "libavcodec/internal.h"
23 #include "avformat.h"
24 #include "internal.h"
25 #include "config.h"
26
27 /* Enable function pointer definitions for runtime loading. */
28 #define AVSC_NO_DECLSPEC
29
30 /* Platform-specific directives for AviSynth vs AvxSynth. */
31 #ifdef _WIN32
32   #include "compat/w32dlfcn.h"
33   #undef EXTERN_C
34   #include "compat/avisynth/avisynth_c.h"
35   #define AVISYNTH_LIB "avisynth"
36   #define USING_AVISYNTH
37 #else
38   #include <dlfcn.h>
39   #include "compat/avisynth/avxsynth_c.h"
40   #define AVISYNTH_NAME "libavxsynth"
41   #define AVISYNTH_LIB AVISYNTH_NAME SLIBSUF
42 #endif
43
44 typedef struct AviSynthLibrary {
45     void *library;
46 #define AVSC_DECLARE_FUNC(name) name ## _func name
47     AVSC_DECLARE_FUNC(avs_bit_blt);
48     AVSC_DECLARE_FUNC(avs_clip_get_error);
49     AVSC_DECLARE_FUNC(avs_create_script_environment);
50     AVSC_DECLARE_FUNC(avs_delete_script_environment);
51     AVSC_DECLARE_FUNC(avs_get_audio);
52     AVSC_DECLARE_FUNC(avs_get_error);
53     AVSC_DECLARE_FUNC(avs_get_frame);
54     AVSC_DECLARE_FUNC(avs_get_version);
55     AVSC_DECLARE_FUNC(avs_get_video_info);
56     AVSC_DECLARE_FUNC(avs_invoke);
57     AVSC_DECLARE_FUNC(avs_release_clip);
58     AVSC_DECLARE_FUNC(avs_release_value);
59     AVSC_DECLARE_FUNC(avs_release_video_frame);
60     AVSC_DECLARE_FUNC(avs_take_clip);
61 #ifdef USING_AVISYNTH
62     AVSC_DECLARE_FUNC(avs_bits_per_pixel);
63     AVSC_DECLARE_FUNC(avs_get_height_p);
64     AVSC_DECLARE_FUNC(avs_get_pitch_p);
65     AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
66     AVSC_DECLARE_FUNC(avs_get_row_size_p);
67     AVSC_DECLARE_FUNC(avs_is_planar_rgb);
68     AVSC_DECLARE_FUNC(avs_is_planar_rgba);
69 #endif
70 #undef AVSC_DECLARE_FUNC
71 } AviSynthLibrary;
72
73 typedef struct AviSynthContext {
74     AVS_ScriptEnvironment *env;
75     AVS_Clip *clip;
76     const AVS_VideoInfo *vi;
77
78     /* avisynth_read_packet_video() iterates over this. */
79     int n_planes;
80     const int *planes;
81
82     int curr_stream;
83     int curr_frame;
84     int64_t curr_sample;
85
86     int error;
87
88     /* Linked list pointers. */
89     struct AviSynthContext *next;
90 } AviSynthContext;
91
92 static const int avs_planes_packed[1] = { 0 };
93 static const int avs_planes_grey[1]   = { AVS_PLANAR_Y };
94 static const int avs_planes_yuv[3]    = { AVS_PLANAR_Y, AVS_PLANAR_U,
95                                           AVS_PLANAR_V };
96 #ifdef USING_AVISYNTH
97 static const int avs_planes_rgb[3]    = { AVS_PLANAR_G, AVS_PLANAR_B,
98                                           AVS_PLANAR_R };
99 static const int avs_planes_yuva[4]   = { AVS_PLANAR_Y, AVS_PLANAR_U,
100                                           AVS_PLANAR_V, AVS_PLANAR_A };
101 static const int avs_planes_rgba[4]   = { AVS_PLANAR_G, AVS_PLANAR_B,
102                                           AVS_PLANAR_R, AVS_PLANAR_A };
103 #endif
104
105 /* A conflict between C++ global objects, atexit, and dynamic loading requires
106  * us to register our own atexit handler to prevent double freeing. */
107 static AviSynthLibrary avs_library;
108 static int avs_atexit_called        = 0;
109
110 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
111 static AviSynthContext *avs_ctx_list = NULL;
112
113 static av_cold void avisynth_atexit_handler(void);
114
115 static av_cold int avisynth_load_library(void)
116 {
117     avs_library.library = dlopen(AVISYNTH_LIB, RTLD_NOW | RTLD_LOCAL);
118     if (!avs_library.library)
119         return AVERROR_UNKNOWN;
120
121 #define LOAD_AVS_FUNC(name, continue_on_fail)                          \
122         avs_library.name =                                             \
123             (void *)dlsym(avs_library.library, #name);                 \
124         if (!continue_on_fail && !avs_library.name)                    \
125             goto fail;
126
127     LOAD_AVS_FUNC(avs_bit_blt, 0);
128     LOAD_AVS_FUNC(avs_clip_get_error, 0);
129     LOAD_AVS_FUNC(avs_create_script_environment, 0);
130     LOAD_AVS_FUNC(avs_delete_script_environment, 0);
131     LOAD_AVS_FUNC(avs_get_audio, 0);
132     LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
133     LOAD_AVS_FUNC(avs_get_frame, 0);
134     LOAD_AVS_FUNC(avs_get_version, 0);
135     LOAD_AVS_FUNC(avs_get_video_info, 0);
136     LOAD_AVS_FUNC(avs_invoke, 0);
137     LOAD_AVS_FUNC(avs_release_clip, 0);
138     LOAD_AVS_FUNC(avs_release_value, 0);
139     LOAD_AVS_FUNC(avs_release_video_frame, 0);
140     LOAD_AVS_FUNC(avs_take_clip, 0);
141 #ifdef USING_AVISYNTH
142     LOAD_AVS_FUNC(avs_bits_per_pixel, 1);
143     LOAD_AVS_FUNC(avs_get_height_p, 1);
144     LOAD_AVS_FUNC(avs_get_pitch_p, 1);
145     LOAD_AVS_FUNC(avs_get_read_ptr_p, 1);
146     LOAD_AVS_FUNC(avs_get_row_size_p, 1);
147     LOAD_AVS_FUNC(avs_is_planar_rgb, 1);
148     LOAD_AVS_FUNC(avs_is_planar_rgba, 1);
149 #endif
150 #undef LOAD_AVS_FUNC
151
152     atexit(avisynth_atexit_handler);
153     return 0;
154
155 fail:
156     dlclose(avs_library.library);
157     return AVERROR_UNKNOWN;
158 }
159
160 /* Note that avisynth_context_create and avisynth_context_destroy
161  * do not allocate or free the actual context! That is taken care of
162  * by libavformat. */
163 static av_cold int avisynth_context_create(AVFormatContext *s)
164 {
165     AviSynthContext *avs = s->priv_data;
166     int ret;
167
168     if (!avs_library.library)
169         if (ret = avisynth_load_library())
170             return ret;
171
172     avs->env = avs_library.avs_create_script_environment(3);
173     if (avs_library.avs_get_error) {
174         const char *error = avs_library.avs_get_error(avs->env);
175         if (error) {
176             av_log(s, AV_LOG_ERROR, "%s\n", error);
177             return AVERROR_UNKNOWN;
178         }
179     }
180
181     if (!avs_ctx_list) {
182         avs_ctx_list = avs;
183     } else {
184         avs->next    = avs_ctx_list;
185         avs_ctx_list = avs;
186     }
187
188     return 0;
189 }
190
191 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
192 {
193     if (avs_atexit_called)
194         return;
195
196     if (avs == avs_ctx_list) {
197         avs_ctx_list = avs->next;
198     } else {
199         AviSynthContext *prev = avs_ctx_list;
200         while (prev->next != avs)
201             prev = prev->next;
202         prev->next = avs->next;
203     }
204
205     if (avs->clip) {
206         avs_library.avs_release_clip(avs->clip);
207         avs->clip = NULL;
208     }
209     if (avs->env) {
210         avs_library.avs_delete_script_environment(avs->env);
211         avs->env = NULL;
212     }
213 }
214
215 static av_cold void avisynth_atexit_handler(void)
216 {
217     AviSynthContext *avs = avs_ctx_list;
218
219     while (avs) {
220         AviSynthContext *next = avs->next;
221         avisynth_context_destroy(avs);
222         avs = next;
223     }
224     dlclose(avs_library.library);
225
226     avs_atexit_called = 1;
227 }
228
229 /* Create AVStream from audio and video data. */
230 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
231 {
232     AviSynthContext *avs = s->priv_data;
233     int planar = 0; // 0: packed, 1: YUV, 2: Y8, 3: Planar RGB, 4: YUVA, 5: Planar RGBA
234
235     st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
236     st->codecpar->codec_id   = AV_CODEC_ID_RAWVIDEO;
237     st->codecpar->width      = avs->vi->width;
238     st->codecpar->height     = avs->vi->height;
239
240     st->avg_frame_rate    = (AVRational) { avs->vi->fps_numerator,
241                                            avs->vi->fps_denominator };
242     st->start_time        = 0;
243     st->duration          = avs->vi->num_frames;
244     st->nb_frames         = avs->vi->num_frames;
245     avpriv_set_pts_info(st, 32, avs->vi->fps_denominator, avs->vi->fps_numerator);
246
247     switch (avs->vi->pixel_type) {
248 #ifdef USING_AVISYNTH
249 /* 10~16-bit YUV pix_fmts (AviSynth+) */
250     case AVS_CS_YUV444P10:
251         st->codecpar->format = AV_PIX_FMT_YUV444P10;
252         planar               = 1;
253         break;
254     case AVS_CS_YUV422P10:
255         st->codecpar->format = AV_PIX_FMT_YUV422P10;
256         planar               = 1;
257         break;
258     case AVS_CS_YUV420P10:
259         st->codecpar->format = AV_PIX_FMT_YUV420P10;
260         planar               = 1;
261         break;
262     case AVS_CS_YUV444P12:
263         st->codecpar->format = AV_PIX_FMT_YUV444P12;
264         planar               = 1;
265         break;
266     case AVS_CS_YUV422P12:
267         st->codecpar->format = AV_PIX_FMT_YUV422P12;
268         planar               = 1;
269         break;
270     case AVS_CS_YUV420P12:
271         st->codecpar->format = AV_PIX_FMT_YUV420P12;
272         planar               = 1;
273         break;
274     case AVS_CS_YUV444P14:
275         st->codecpar->format = AV_PIX_FMT_YUV444P14;
276         planar               = 1;
277         break;
278     case AVS_CS_YUV422P14:
279         st->codecpar->format = AV_PIX_FMT_YUV422P14;
280         planar               = 1;
281         break;
282     case AVS_CS_YUV420P14:
283         st->codecpar->format = AV_PIX_FMT_YUV420P14;
284         planar               = 1;
285         break;
286     case AVS_CS_YUV444P16:
287         st->codecpar->format = AV_PIX_FMT_YUV444P16;
288         planar               = 1;
289         break;
290     case AVS_CS_YUV422P16:
291         st->codecpar->format = AV_PIX_FMT_YUV422P16;
292         planar               = 1;
293         break;
294     case AVS_CS_YUV420P16:
295         st->codecpar->format = AV_PIX_FMT_YUV420P16;
296         planar               = 1;
297         break;
298 /* 8~16-bit YUV pix_fmts with Alpha (AviSynth+) */
299     case AVS_CS_YUVA444:
300         st->codecpar->format = AV_PIX_FMT_YUVA444P;
301         planar               = 4;
302         break;
303     case AVS_CS_YUVA422:
304         st->codecpar->format = AV_PIX_FMT_YUVA422P;
305         planar               = 4;
306         break;
307     case AVS_CS_YUVA420:
308         st->codecpar->format = AV_PIX_FMT_YUVA420P;
309         planar               = 4;
310         break;
311     case AVS_CS_YUVA444P10:
312         st->codecpar->format = AV_PIX_FMT_YUVA444P10;
313         planar               = 4;
314         break;
315     case AVS_CS_YUVA422P10:
316         st->codecpar->format = AV_PIX_FMT_YUVA422P10;
317         planar               = 4;
318         break;
319     case AVS_CS_YUVA420P10:
320         st->codecpar->format = AV_PIX_FMT_YUVA420P10;
321         planar               = 4;
322         break;
323     case AVS_CS_YUVA444P16:
324         st->codecpar->format = AV_PIX_FMT_YUVA444P16;
325         planar               = 4;
326         break;
327     case AVS_CS_YUVA422P16:
328         st->codecpar->format = AV_PIX_FMT_YUVA422P16;
329         planar               = 4;
330         break;
331     case AVS_CS_YUVA420P16:
332         st->codecpar->format = AV_PIX_FMT_YUVA420P16;
333         planar               = 4;
334         break;
335 /* Planar RGB pix_fmts (AviSynth+)  */
336     case AVS_CS_RGBP:
337         st->codecpar->format = AV_PIX_FMT_GBRP;
338         planar               = 3;
339         break;
340     case AVS_CS_RGBP10:
341         st->codecpar->format = AV_PIX_FMT_GBRP10;
342         planar               = 3;
343         break;
344     case AVS_CS_RGBP12:
345         st->codecpar->format = AV_PIX_FMT_GBRP12;
346         planar               = 3;
347         break;
348     case AVS_CS_RGBP14:
349         st->codecpar->format = AV_PIX_FMT_GBRP14;
350         planar               = 3;
351         break;
352     case AVS_CS_RGBP16:
353         st->codecpar->format = AV_PIX_FMT_GBRP16;
354         planar               = 3;
355         break;
356 /* Planar RGB pix_fmts with Alpha (AviSynth+) */
357     case AVS_CS_RGBAP:
358         st->codecpar->format = AV_PIX_FMT_GBRAP;
359         planar               = 5;
360         break;
361     case AVS_CS_RGBAP10:
362         st->codecpar->format = AV_PIX_FMT_GBRAP10;
363         planar               = 5;
364         break;
365     case AVS_CS_RGBAP12:
366         st->codecpar->format = AV_PIX_FMT_GBRAP12;
367         planar               = 5;
368         break;
369     case AVS_CS_RGBAP16:
370         st->codecpar->format = AV_PIX_FMT_GBRAP16;
371         planar               = 5;
372         break;
373 /* GRAY16 (AviSynth+) */
374     case AVS_CS_Y16:
375         st->codecpar->format = AV_PIX_FMT_GRAY16;
376         planar               = 2;
377         break;
378 /* pix_fmts added in AviSynth 2.6 */
379     case AVS_CS_YV24:
380         st->codecpar->format = AV_PIX_FMT_YUV444P;
381         planar               = 1;
382         break;
383     case AVS_CS_YV16:
384         st->codecpar->format = AV_PIX_FMT_YUV422P;
385         planar               = 1;
386         break;
387     case AVS_CS_YV411:
388         st->codecpar->format = AV_PIX_FMT_YUV411P;
389         planar               = 1;
390         break;
391     case AVS_CS_Y8:
392         st->codecpar->format = AV_PIX_FMT_GRAY8;
393         planar               = 2;
394         break;
395 /* 16-bit packed RGB pix_fmts (AviSynth+) */
396     case AVS_CS_BGR48:
397         st->codecpar->format = AV_PIX_FMT_BGR48;
398         break;
399     case AVS_CS_BGR64:
400         st->codecpar->format = AV_PIX_FMT_BGRA64;
401         break;
402 #endif
403 /* AviSynth 2.5 and AvxSynth pix_fmts */
404     case AVS_CS_BGR24:
405         st->codecpar->format = AV_PIX_FMT_BGR24;
406         break;
407     case AVS_CS_BGR32:
408         st->codecpar->format = AV_PIX_FMT_RGB32;
409         break;
410     case AVS_CS_YUY2:
411         st->codecpar->format = AV_PIX_FMT_YUYV422;
412         break;
413     case AVS_CS_YV12:
414         st->codecpar->format = AV_PIX_FMT_YUV420P;
415         planar               = 1;
416         break;
417     case AVS_CS_I420: // Is this even used anywhere?
418         st->codecpar->format = AV_PIX_FMT_YUV420P;
419         planar               = 1;
420         break;
421     default:
422         av_log(s, AV_LOG_ERROR,
423                "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
424         avs->error = 1;
425         return AVERROR_UNKNOWN;
426     }
427
428     switch (planar) {
429 #ifdef USING_AVISYNTH
430     case 5: // Planar RGB + Alpha
431         avs->n_planes = 4;
432         avs->planes   = avs_planes_rgba;
433         break;
434     case 4: // YUV + Alpha
435         avs->n_planes = 4;
436         avs->planes   = avs_planes_yuva;
437         break;
438     case 3: // Planar RGB
439         avs->n_planes = 3;
440         avs->planes   = avs_planes_rgb;
441         break;
442 #endif
443     case 2: // Y8
444         avs->n_planes = 1;
445         avs->planes   = avs_planes_grey;
446         break;
447     case 1: // YUV
448         avs->n_planes = 3;
449         avs->planes   = avs_planes_yuv;
450         break;
451     default:
452         avs->n_planes = 1;
453         avs->planes   = avs_planes_packed;
454     }
455     return 0;
456 }
457
458 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
459 {
460     AviSynthContext *avs = s->priv_data;
461
462     st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
463     st->codecpar->sample_rate = avs->vi->audio_samples_per_second;
464     st->codecpar->channels    = avs->vi->nchannels;
465     st->duration              = avs->vi->num_audio_samples;
466     avpriv_set_pts_info(st, 64, 1, avs->vi->audio_samples_per_second);
467
468     switch (avs->vi->sample_type) {
469     case AVS_SAMPLE_INT8:
470         st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
471         break;
472     case AVS_SAMPLE_INT16:
473         st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
474         break;
475     case AVS_SAMPLE_INT24:
476         st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
477         break;
478     case AVS_SAMPLE_INT32:
479         st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
480         break;
481     case AVS_SAMPLE_FLOAT:
482         st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
483         break;
484     default:
485         av_log(s, AV_LOG_ERROR,
486                "unknown AviSynth sample type %d\n", avs->vi->sample_type);
487         avs->error = 1;
488         return AVERROR_UNKNOWN;
489     }
490     return 0;
491 }
492
493 static int avisynth_create_stream(AVFormatContext *s)
494 {
495     AviSynthContext *avs = s->priv_data;
496     AVStream *st;
497     int ret;
498     int id = 0;
499
500     if (avs_has_video(avs->vi)) {
501         st = avformat_new_stream(s, NULL);
502         if (!st)
503             return AVERROR_UNKNOWN;
504         st->id = id++;
505         if (ret = avisynth_create_stream_video(s, st))
506             return ret;
507     }
508     if (avs_has_audio(avs->vi)) {
509         st = avformat_new_stream(s, NULL);
510         if (!st)
511             return AVERROR_UNKNOWN;
512         st->id = id++;
513         if (ret = avisynth_create_stream_audio(s, st))
514             return ret;
515     }
516     return 0;
517 }
518
519 static int avisynth_open_file(AVFormatContext *s)
520 {
521     AviSynthContext *avs = s->priv_data;
522     AVS_Value arg, val;
523     int ret;
524 #ifdef USING_AVISYNTH
525     char filename_ansi[MAX_PATH * 4];
526     wchar_t filename_wc[MAX_PATH * 4];
527 #endif
528
529     if (ret = avisynth_context_create(s))
530         return ret;
531
532 #ifdef USING_AVISYNTH
533     /* Convert UTF-8 to ANSI code page */
534     MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
535     WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
536                         MAX_PATH * 4, NULL, NULL);
537     arg = avs_new_value_string(filename_ansi);
538 #else
539     arg = avs_new_value_string(s->filename);
540 #endif
541     val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
542     if (avs_is_error(val)) {
543         av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
544         ret = AVERROR_UNKNOWN;
545         goto fail;
546     }
547     if (!avs_is_clip(val)) {
548         av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
549         ret = AVERROR_UNKNOWN;
550         goto fail;
551     }
552
553     avs->clip = avs_library.avs_take_clip(val, avs->env);
554     avs->vi   = avs_library.avs_get_video_info(avs->clip);
555
556 #ifdef USING_AVISYNTH
557     /* On Windows, FFmpeg supports AviSynth interface version 6 or higher.
558      * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
559      * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
560      * as interface version 3 like 2.5.8, this needs to be special-cased. */
561
562     if (avs_library.avs_get_version(avs->clip) < 6) {
563         av_log(s, AV_LOG_ERROR,
564                "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
565         ret = AVERROR_UNKNOWN;
566         goto fail;
567     }
568 #endif
569
570     /* Release the AVS_Value as it will go out of scope. */
571     avs_library.avs_release_value(val);
572
573     if (ret = avisynth_create_stream(s))
574         goto fail;
575
576     return 0;
577
578 fail:
579     avisynth_context_destroy(avs);
580     return ret;
581 }
582
583 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
584                                  AVPacket *pkt, int *discard)
585 {
586     AviSynthContext *avs = s->priv_data;
587
588     avs->curr_stream++;
589     avs->curr_stream %= s->nb_streams;
590
591     *st = s->streams[avs->curr_stream];
592     if ((*st)->discard == AVDISCARD_ALL)
593         *discard = 1;
594     else
595         *discard = 0;
596
597     return;
598 }
599
600 /* Copy AviSynth clip data into an AVPacket. */
601 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
602                                       int discard)
603 {
604     AviSynthContext *avs = s->priv_data;
605     AVS_VideoFrame *frame;
606     unsigned char *dst_p;
607     const unsigned char *src_p;
608     int n, i, plane, rowsize, planeheight, pitch, bits;
609     const char *error;
610
611     if (avs->curr_frame >= avs->vi->num_frames)
612         return AVERROR_EOF;
613
614     /* This must happen even if the stream is discarded to prevent desync. */
615     n = avs->curr_frame++;
616     if (discard)
617         return 0;
618
619 #ifdef USING_AVISYNTH
620     /* Detect whether we're using AviSynth 2.6 or AviSynth+ by
621      * looking for whether avs_is_planar_rgb exists. */
622
623     int avsplus;
624
625     if (GetProcAddress(avs_library.library, "avs_is_planar_rgb") == NULL)
626         avsplus = 0;
627     else
628         avsplus = 1;
629
630     /* avs_bits_per_pixel changed to AVSC_API with AviSynth 2.6, which
631      * requires going through avs_library, while AvxSynth has it under
632      * the older AVSC_INLINE type, so special-case this. */
633
634     bits = avs_library.avs_bits_per_pixel(avs->vi);
635 #else
636     bits = avs_bits_per_pixel(avs->vi);
637 #endif
638
639     /* Without the cast to int64_t, calculation overflows at about 9k x 9k
640      * resolution. */
641     pkt->size = (((int64_t)avs->vi->width *
642                   (int64_t)avs->vi->height) * bits) / 8;
643     if (!pkt->size)
644         return AVERROR_UNKNOWN;
645
646     if (av_new_packet(pkt, pkt->size) < 0)
647         return AVERROR(ENOMEM);
648
649     pkt->pts      = n;
650     pkt->dts      = n;
651     pkt->duration = 1;
652     pkt->stream_index = avs->curr_stream;
653
654     frame = avs_library.avs_get_frame(avs->clip, n);
655     error = avs_library.avs_clip_get_error(avs->clip);
656     if (error) {
657         av_log(s, AV_LOG_ERROR, "%s\n", error);
658         avs->error = 1;
659         av_packet_unref(pkt);
660         return AVERROR_UNKNOWN;
661     }
662
663     dst_p = pkt->data;
664     for (i = 0; i < avs->n_planes; i++) {
665         plane = avs->planes[i];
666 #ifdef USING_AVISYNTH
667         src_p = avs_library.avs_get_read_ptr_p(frame, plane);
668         pitch = avs_library.avs_get_pitch_p(frame, plane);
669
670         rowsize     = avs_library.avs_get_row_size_p(frame, plane);
671         planeheight = avs_library.avs_get_height_p(frame, plane);
672 #else
673         src_p = avs_get_read_ptr_p(frame, plane);
674         pitch = avs_get_pitch_p(frame, plane);
675
676         rowsize     = avs_get_row_size_p(frame, plane);
677         planeheight = avs_get_height_p(frame, plane);
678 #endif
679
680         /* Flip RGB video. */
681         if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
682             src_p = src_p + (planeheight - 1) * pitch;
683             pitch = -pitch;
684         }
685
686 #ifdef USING_AVISYNTH
687         /* Flip Planar RGB video. */
688         if (avsplus && (avs_library.avs_is_planar_rgb(avs->vi) ||
689                         avs_library.avs_is_planar_rgba(avs->vi))) {
690             src_p = src_p + (planeheight - 1) * pitch;
691             pitch = -pitch;
692         }
693 #endif
694
695         avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
696                                  rowsize, planeheight);
697         dst_p += rowsize * planeheight;
698     }
699
700     avs_library.avs_release_video_frame(frame);
701     return 0;
702 }
703
704 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
705                                       int discard)
706 {
707     AviSynthContext *avs = s->priv_data;
708     AVRational fps, samplerate;
709     int samples;
710     int64_t n;
711     const char *error;
712
713     if (avs->curr_sample >= avs->vi->num_audio_samples)
714         return AVERROR_EOF;
715
716     fps.num        = avs->vi->fps_numerator;
717     fps.den        = avs->vi->fps_denominator;
718     samplerate.num = avs->vi->audio_samples_per_second;
719     samplerate.den = 1;
720
721     if (avs_has_video(avs->vi)) {
722         if (avs->curr_frame < avs->vi->num_frames)
723             samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
724                       avs->curr_sample;
725         else
726             samples = av_rescale_q(1, samplerate, fps);
727     } else {
728         samples = 1000;
729     }
730
731     /* After seeking, audio may catch up with video. */
732     if (samples <= 0) {
733         pkt->size = 0;
734         pkt->data = NULL;
735         return 0;
736     }
737
738     if (avs->curr_sample + samples > avs->vi->num_audio_samples)
739         samples = avs->vi->num_audio_samples - avs->curr_sample;
740
741     /* This must happen even if the stream is discarded to prevent desync. */
742     n                 = avs->curr_sample;
743     avs->curr_sample += samples;
744     if (discard)
745         return 0;
746
747     pkt->size = avs_bytes_per_channel_sample(avs->vi) *
748                 samples * avs->vi->nchannels;
749     if (!pkt->size)
750         return AVERROR_UNKNOWN;
751
752     if (av_new_packet(pkt, pkt->size) < 0)
753         return AVERROR(ENOMEM);
754
755     pkt->pts      = n;
756     pkt->dts      = n;
757     pkt->duration = samples;
758     pkt->stream_index = avs->curr_stream;
759
760     avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
761     error = avs_library.avs_clip_get_error(avs->clip);
762     if (error) {
763         av_log(s, AV_LOG_ERROR, "%s\n", error);
764         avs->error = 1;
765         av_packet_unref(pkt);
766         return AVERROR_UNKNOWN;
767     }
768     return 0;
769 }
770
771 static av_cold int avisynth_read_header(AVFormatContext *s)
772 {
773     int ret;
774
775     // Calling library must implement a lock for thread-safe opens.
776     if (ret = avpriv_lock_avformat())
777         return ret;
778
779     if (ret = avisynth_open_file(s)) {
780         avpriv_unlock_avformat();
781         return ret;
782     }
783
784     avpriv_unlock_avformat();
785     return 0;
786 }
787
788 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
789 {
790     AviSynthContext *avs = s->priv_data;
791     AVStream *st;
792     int discard = 0;
793     int ret;
794
795     if (avs->error)
796         return AVERROR_UNKNOWN;
797
798     /* If either stream reaches EOF, try to read the other one before
799      * giving up. */
800     avisynth_next_stream(s, &st, pkt, &discard);
801     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
802         ret = avisynth_read_packet_video(s, pkt, discard);
803         if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
804             avisynth_next_stream(s, &st, pkt, &discard);
805             return avisynth_read_packet_audio(s, pkt, discard);
806         }
807     } else {
808         ret = avisynth_read_packet_audio(s, pkt, discard);
809         if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
810             avisynth_next_stream(s, &st, pkt, &discard);
811             return avisynth_read_packet_video(s, pkt, discard);
812         }
813     }
814
815     return ret;
816 }
817
818 static av_cold int avisynth_read_close(AVFormatContext *s)
819 {
820     if (avpriv_lock_avformat())
821         return AVERROR_UNKNOWN;
822
823     avisynth_context_destroy(s->priv_data);
824     avpriv_unlock_avformat();
825     return 0;
826 }
827
828 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
829                               int64_t timestamp, int flags)
830 {
831     AviSynthContext *avs = s->priv_data;
832     AVStream *st;
833     AVRational fps, samplerate;
834
835     if (avs->error)
836         return AVERROR_UNKNOWN;
837
838     fps        = (AVRational) { avs->vi->fps_numerator,
839                                 avs->vi->fps_denominator };
840     samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
841
842     st = s->streams[stream_index];
843     if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
844         /* AviSynth frame counts are signed int. */
845         if ((timestamp >= avs->vi->num_frames) ||
846             (timestamp > INT_MAX)              ||
847             (timestamp < 0))
848             return AVERROR_EOF;
849         avs->curr_frame = timestamp;
850         if (avs_has_audio(avs->vi))
851             avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
852     } else {
853         if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
854             return AVERROR_EOF;
855         /* Force frame granularity for seeking. */
856         if (avs_has_video(avs->vi)) {
857             avs->curr_frame  = av_rescale_q(timestamp, fps, samplerate);
858             avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
859         } else {
860             avs->curr_sample = timestamp;
861         }
862     }
863
864     return 0;
865 }
866
867 AVInputFormat ff_avisynth_demuxer = {
868     .name           = "avisynth",
869     .long_name      = NULL_IF_CONFIG_SMALL("AviSynth script"),
870     .priv_data_size = sizeof(AviSynthContext),
871     .read_header    = avisynth_read_header,
872     .read_packet    = avisynth_read_packet,
873     .read_close     = avisynth_read_close,
874     .read_seek      = avisynth_read_seek,
875     .extensions     = "avs",
876 };