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