]> git.sesse.net Git - ffmpeg/blob - libavformat/avisynth.c
Merge commit 'df528b11ac607de13a7c438f2a51f2119f71a03c'
[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
26 /* Enable function pointer definitions for runtime loading. */
27 #define AVSC_NO_DECLSPEC
28
29 /* Platform-specific directives for AviSynth vs AvxSynth. */
30 #ifdef _WIN32
31   #include <windows.h>
32   #undef EXTERN_C
33   #include "compat/avisynth/avisynth_c.h"
34   #define AVISYNTH_LIB "avisynth"
35   #define USING_AVISYNTH
36 #else
37   #include <dlfcn.h>
38   #include "compat/avisynth/avxsynth_c.h"
39     #if defined (__APPLE__)
40       #define AVISYNTH_LIB "libavxsynth.dylib"
41     #else
42       #define AVISYNTH_LIB "libavxsynth.so"
43     #endif
44
45   #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_LOCAL)
46   #define GetProcAddress dlsym
47   #define FreeLibrary dlclose
48 #endif
49
50 typedef struct AviSynthLibrary {
51     void *library;
52 #define AVSC_DECLARE_FUNC(name) name ## _func name
53     AVSC_DECLARE_FUNC(avs_bit_blt);
54     AVSC_DECLARE_FUNC(avs_clip_get_error);
55     AVSC_DECLARE_FUNC(avs_create_script_environment);
56     AVSC_DECLARE_FUNC(avs_delete_script_environment);
57     AVSC_DECLARE_FUNC(avs_get_audio);
58     AVSC_DECLARE_FUNC(avs_get_error);
59     AVSC_DECLARE_FUNC(avs_get_frame);
60     AVSC_DECLARE_FUNC(avs_get_version);
61     AVSC_DECLARE_FUNC(avs_get_video_info);
62     AVSC_DECLARE_FUNC(avs_invoke);
63     AVSC_DECLARE_FUNC(avs_release_clip);
64     AVSC_DECLARE_FUNC(avs_release_value);
65     AVSC_DECLARE_FUNC(avs_release_video_frame);
66     AVSC_DECLARE_FUNC(avs_take_clip);
67 #ifdef USING_AVISYNTH
68     AVSC_DECLARE_FUNC(avs_bits_per_pixel);
69     AVSC_DECLARE_FUNC(avs_get_height_p);
70     AVSC_DECLARE_FUNC(avs_get_pitch_p);
71     AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
72     AVSC_DECLARE_FUNC(avs_get_row_size_p);
73     AVSC_DECLARE_FUNC(avs_is_yv24);
74     AVSC_DECLARE_FUNC(avs_is_yv16);
75     AVSC_DECLARE_FUNC(avs_is_yv411);
76     AVSC_DECLARE_FUNC(avs_is_y8);
77 #endif
78 #undef AVSC_DECLARE_FUNC
79 } AviSynthLibrary;
80
81 typedef struct AviSynthContext {
82     AVS_ScriptEnvironment *env;
83     AVS_Clip *clip;
84     const AVS_VideoInfo *vi;
85
86     /* avisynth_read_packet_video() iterates over this. */
87     int n_planes;
88     const int *planes;
89
90     int curr_stream;
91     int curr_frame;
92     int64_t curr_sample;
93
94     int error;
95
96     /* Linked list pointers. */
97     struct AviSynthContext *next;
98 } AviSynthContext;
99
100 static const int avs_planes_packed[1] = { 0 };
101 static const int avs_planes_grey[1]   = { AVS_PLANAR_Y };
102 static const int avs_planes_yuv[3]    = { AVS_PLANAR_Y, AVS_PLANAR_U,
103                                           AVS_PLANAR_V };
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 = LoadLibrary(AVISYNTH_LIB);
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 *)GetProcAddress(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_yv24, 1);
148     LOAD_AVS_FUNC(avs_is_yv16, 1);
149     LOAD_AVS_FUNC(avs_is_yv411, 1);
150     LOAD_AVS_FUNC(avs_is_y8, 1);
151 #endif
152 #undef LOAD_AVS_FUNC
153
154     atexit(avisynth_atexit_handler);
155     return 0;
156
157 fail:
158     FreeLibrary(avs_library.library);
159     return AVERROR_UNKNOWN;
160 }
161
162 /* Note that avisynth_context_create and avisynth_context_destroy
163  * do not allocate or free the actual context! That is taken care of
164  * by libavformat. */
165 static av_cold int avisynth_context_create(AVFormatContext *s)
166 {
167     AviSynthContext *avs = s->priv_data;
168     int ret;
169
170     if (!avs_library.library)
171         if (ret = avisynth_load_library())
172             return ret;
173
174     avs->env = avs_library.avs_create_script_environment(3);
175     if (avs_library.avs_get_error) {
176         const char *error = avs_library.avs_get_error(avs->env);
177         if (error) {
178             av_log(s, AV_LOG_ERROR, "%s\n", error);
179             return AVERROR_UNKNOWN;
180         }
181     }
182
183     if (!avs_ctx_list) {
184         avs_ctx_list = avs;
185     } else {
186         avs->next    = avs_ctx_list;
187         avs_ctx_list = avs;
188     }
189
190     return 0;
191 }
192
193 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
194 {
195     if (avs_atexit_called)
196         return;
197
198     if (avs == avs_ctx_list) {
199         avs_ctx_list = avs->next;
200     } else {
201         AviSynthContext *prev = avs_ctx_list;
202         while (prev->next != avs)
203             prev = prev->next;
204         prev->next = avs->next;
205     }
206
207     if (avs->clip) {
208         avs_library.avs_release_clip(avs->clip);
209         avs->clip = NULL;
210     }
211     if (avs->env) {
212         avs_library.avs_delete_script_environment(avs->env);
213         avs->env = NULL;
214     }
215 }
216
217 static av_cold void avisynth_atexit_handler(void)
218 {
219     AviSynthContext *avs = avs_ctx_list;
220
221     while (avs) {
222         AviSynthContext *next = avs->next;
223         avisynth_context_destroy(avs);
224         avs = next;
225     }
226     FreeLibrary(avs_library.library);
227
228     avs_atexit_called = 1;
229 }
230
231 /* Create AVStream from audio and video data. */
232 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
233 {
234     AviSynthContext *avs = s->priv_data;
235     int planar = 0; // 0: packed, 1: YUV, 2: Y8
236
237     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
238     st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
239     st->codec->width      = avs->vi->width;
240     st->codec->height     = avs->vi->height;
241
242     st->time_base         = (AVRational) { avs->vi->fps_denominator,
243                                            avs->vi->fps_numerator };
244     st->avg_frame_rate    = (AVRational) { avs->vi->fps_numerator,
245                                            avs->vi->fps_denominator };
246     st->start_time        = 0;
247     st->duration          = avs->vi->num_frames;
248     st->nb_frames         = avs->vi->num_frames;
249
250     switch (avs->vi->pixel_type) {
251 #ifdef USING_AVISYNTH
252     case AVS_CS_YV24:
253         st->codec->pix_fmt = AV_PIX_FMT_YUV444P;
254         planar             = 1;
255         break;
256     case AVS_CS_YV16:
257         st->codec->pix_fmt = AV_PIX_FMT_YUV422P;
258         planar             = 1;
259         break;
260     case AVS_CS_YV411:
261         st->codec->pix_fmt = AV_PIX_FMT_YUV411P;
262         planar             = 1;
263         break;
264     case AVS_CS_Y8:
265         st->codec->pix_fmt = AV_PIX_FMT_GRAY8;
266         planar             = 2;
267         break;
268 #endif
269     case AVS_CS_BGR24:
270         st->codec->pix_fmt = AV_PIX_FMT_BGR24;
271         break;
272     case AVS_CS_BGR32:
273         st->codec->pix_fmt = AV_PIX_FMT_RGB32;
274         break;
275     case AVS_CS_YUY2:
276         st->codec->pix_fmt = AV_PIX_FMT_YUYV422;
277         break;
278     case AVS_CS_YV12:
279         st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
280         planar             = 1;
281         break;
282     case AVS_CS_I420: // Is this even used anywhere?
283         st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
284         planar             = 1;
285         break;
286     default:
287         av_log(s, AV_LOG_ERROR,
288                "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
289         avs->error = 1;
290         return AVERROR_UNKNOWN;
291     }
292
293     switch (planar) {
294     case 2: // Y8
295         avs->n_planes = 1;
296         avs->planes   = avs_planes_grey;
297         break;
298     case 1: // YUV
299         avs->n_planes = 3;
300         avs->planes   = avs_planes_yuv;
301         break;
302     default:
303         avs->n_planes = 1;
304         avs->planes   = avs_planes_packed;
305     }
306     return 0;
307 }
308
309 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
310 {
311     AviSynthContext *avs = s->priv_data;
312
313     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
314     st->codec->sample_rate = avs->vi->audio_samples_per_second;
315     st->codec->channels    = avs->vi->nchannels;
316     st->time_base          = (AVRational) { 1,
317                                             avs->vi->audio_samples_per_second };
318     st->duration           = avs->vi->num_audio_samples;
319
320     switch (avs->vi->sample_type) {
321     case AVS_SAMPLE_INT8:
322         st->codec->codec_id = AV_CODEC_ID_PCM_U8;
323         break;
324     case AVS_SAMPLE_INT16:
325         st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
326         break;
327     case AVS_SAMPLE_INT24:
328         st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
329         break;
330     case AVS_SAMPLE_INT32:
331         st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
332         break;
333     case AVS_SAMPLE_FLOAT:
334         st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
335         break;
336     default:
337         av_log(s, AV_LOG_ERROR,
338                "unknown AviSynth sample type %d\n", avs->vi->sample_type);
339         avs->error = 1;
340         return AVERROR_UNKNOWN;
341     }
342     return 0;
343 }
344
345 static int avisynth_create_stream(AVFormatContext *s)
346 {
347     AviSynthContext *avs = s->priv_data;
348     AVStream *st;
349     int ret;
350     int id = 0;
351
352     if (avs_has_video(avs->vi)) {
353         st = avformat_new_stream(s, NULL);
354         if (!st)
355             return AVERROR_UNKNOWN;
356         st->id = id++;
357         if (ret = avisynth_create_stream_video(s, st))
358             return ret;
359     }
360     if (avs_has_audio(avs->vi)) {
361         st = avformat_new_stream(s, NULL);
362         if (!st)
363             return AVERROR_UNKNOWN;
364         st->id = id++;
365         if (ret = avisynth_create_stream_audio(s, st))
366             return ret;
367     }
368     return 0;
369 }
370
371 static int avisynth_open_file(AVFormatContext *s)
372 {
373     AviSynthContext *avs = s->priv_data;
374     AVS_Value arg, val;
375     int ret;
376 #ifdef USING_AVISYNTH
377     char filename_ansi[MAX_PATH * 4];
378     wchar_t filename_wc[MAX_PATH * 4];
379 #endif
380
381     if (ret = avisynth_context_create(s))
382         return ret;
383
384 #ifdef USING_AVISYNTH
385     /* Convert UTF-8 to ANSI code page */
386     MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
387     WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
388                         MAX_PATH * 4, NULL, NULL);
389     arg = avs_new_value_string(filename_ansi);
390 #else
391     arg = avs_new_value_string(s->filename);
392 #endif
393     val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
394     if (avs_is_error(val)) {
395         av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
396         ret = AVERROR_UNKNOWN;
397         goto fail;
398     }
399     if (!avs_is_clip(val)) {
400         av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
401         ret = AVERROR_UNKNOWN;
402         goto fail;
403     }
404
405     avs->clip = avs_library.avs_take_clip(val, avs->env);
406     avs->vi   = avs_library.avs_get_video_info(avs->clip);
407
408 #ifdef USING_AVISYNTH
409     /* On Windows, FFmpeg supports AviSynth interface version 6 or higher.
410      * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
411      * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
412      * as interface version 3 like 2.5.8, this needs to be special-cased. */
413
414     if (avs_library.avs_get_version(avs->clip) < 6) {
415         av_log(s, AV_LOG_ERROR,
416                "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
417         ret = AVERROR_UNKNOWN;
418         goto fail;
419     }
420 #endif
421
422     /* Release the AVS_Value as it will go out of scope. */
423     avs_library.avs_release_value(val);
424
425     if (ret = avisynth_create_stream(s))
426         goto fail;
427
428     return 0;
429
430 fail:
431     avisynth_context_destroy(avs);
432     return ret;
433 }
434
435 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
436                                  AVPacket *pkt, int *discard)
437 {
438     AviSynthContext *avs = s->priv_data;
439
440     avs->curr_stream++;
441     avs->curr_stream %= s->nb_streams;
442
443     *st = s->streams[avs->curr_stream];
444     if ((*st)->discard == AVDISCARD_ALL)
445         *discard = 1;
446     else
447         *discard = 0;
448
449     return;
450 }
451
452 /* Copy AviSynth clip data into an AVPacket. */
453 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
454                                       int discard)
455 {
456     AviSynthContext *avs = s->priv_data;
457     AVS_VideoFrame *frame;
458     unsigned char *dst_p;
459     const unsigned char *src_p;
460     int n, i, plane, rowsize, planeheight, pitch, bits;
461     const char *error;
462
463     if (avs->curr_frame >= avs->vi->num_frames)
464         return AVERROR_EOF;
465
466     /* This must happen even if the stream is discarded to prevent desync. */
467     n = avs->curr_frame++;
468     if (discard)
469         return 0;
470
471 #ifdef USING_AVISYNTH
472     /* Define the bpp values for the new AviSynth 2.6 colorspaces.
473      * Since AvxSynth doesn't have these functions, special-case
474      * it in order to avoid implicit declaration errors. */
475
476     if (avs_library.avs_is_yv24(avs->vi))
477         bits = 24;
478     else if (avs_library.avs_is_yv16(avs->vi))
479         bits = 16;
480     else if (avs_library.avs_is_yv411(avs->vi))
481         bits = 12;
482     else if (avs_library.avs_is_y8(avs->vi))
483         bits = 8;
484     else
485         bits = avs_library.avs_bits_per_pixel(avs->vi);
486 #else
487     bits = avs_bits_per_pixel(avs->vi);
488 #endif
489
490     /* Without the cast to int64_t, calculation overflows at about 9k x 9k
491      * resolution. */
492     pkt->size = (((int64_t)avs->vi->width *
493                   (int64_t)avs->vi->height) * bits) / 8;
494     if (!pkt->size)
495         return AVERROR_UNKNOWN;
496
497     if (av_new_packet(pkt, pkt->size) < 0)
498         return AVERROR(ENOMEM);
499
500     pkt->pts      = n;
501     pkt->dts      = n;
502     pkt->duration = 1;
503     pkt->stream_index = avs->curr_stream;
504
505     frame = avs_library.avs_get_frame(avs->clip, n);
506     error = avs_library.avs_clip_get_error(avs->clip);
507     if (error) {
508         av_log(s, AV_LOG_ERROR, "%s\n", error);
509         avs->error = 1;
510         av_packet_unref(pkt);
511         return AVERROR_UNKNOWN;
512     }
513
514     dst_p = pkt->data;
515     for (i = 0; i < avs->n_planes; i++) {
516         plane = avs->planes[i];
517 #ifdef USING_AVISYNTH
518         src_p = avs_library.avs_get_read_ptr_p(frame, plane);
519         pitch = avs_library.avs_get_pitch_p(frame, plane);
520
521         rowsize     = avs_library.avs_get_row_size_p(frame, plane);
522         planeheight = avs_library.avs_get_height_p(frame, plane);
523 #else
524         src_p = avs_get_read_ptr_p(frame, plane);
525         pitch = avs_get_pitch_p(frame, plane);
526
527         rowsize     = avs_get_row_size_p(frame, plane);
528         planeheight = avs_get_height_p(frame, plane);
529 #endif
530
531         /* Flip RGB video. */
532         if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
533             src_p = src_p + (planeheight - 1) * pitch;
534             pitch = -pitch;
535         }
536
537         avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
538                                  rowsize, planeheight);
539         dst_p += rowsize * planeheight;
540     }
541
542     avs_library.avs_release_video_frame(frame);
543     return 0;
544 }
545
546 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
547                                       int discard)
548 {
549     AviSynthContext *avs = s->priv_data;
550     AVRational fps, samplerate;
551     int samples;
552     int64_t n;
553     const char *error;
554
555     if (avs->curr_sample >= avs->vi->num_audio_samples)
556         return AVERROR_EOF;
557
558     fps.num        = avs->vi->fps_numerator;
559     fps.den        = avs->vi->fps_denominator;
560     samplerate.num = avs->vi->audio_samples_per_second;
561     samplerate.den = 1;
562
563     if (avs_has_video(avs->vi)) {
564         if (avs->curr_frame < avs->vi->num_frames)
565             samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
566                       avs->curr_sample;
567         else
568             samples = av_rescale_q(1, samplerate, fps);
569     } else {
570         samples = 1000;
571     }
572
573     /* After seeking, audio may catch up with video. */
574     if (samples <= 0) {
575         pkt->size = 0;
576         pkt->data = NULL;
577         return 0;
578     }
579
580     if (avs->curr_sample + samples > avs->vi->num_audio_samples)
581         samples = avs->vi->num_audio_samples - avs->curr_sample;
582
583     /* This must happen even if the stream is discarded to prevent desync. */
584     n                 = avs->curr_sample;
585     avs->curr_sample += samples;
586     if (discard)
587         return 0;
588
589     pkt->size = avs_bytes_per_channel_sample(avs->vi) *
590                 samples * avs->vi->nchannels;
591     if (!pkt->size)
592         return AVERROR_UNKNOWN;
593
594     if (av_new_packet(pkt, pkt->size) < 0)
595         return AVERROR(ENOMEM);
596
597     pkt->pts      = n;
598     pkt->dts      = n;
599     pkt->duration = samples;
600     pkt->stream_index = avs->curr_stream;
601
602     avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
603     error = avs_library.avs_clip_get_error(avs->clip);
604     if (error) {
605         av_log(s, AV_LOG_ERROR, "%s\n", error);
606         avs->error = 1;
607         av_packet_unref(pkt);
608         return AVERROR_UNKNOWN;
609     }
610     return 0;
611 }
612
613 static av_cold int avisynth_read_header(AVFormatContext *s)
614 {
615     int ret;
616
617     // Calling library must implement a lock for thread-safe opens.
618     if (ret = avpriv_lock_avformat())
619         return ret;
620
621     if (ret = avisynth_open_file(s)) {
622         avpriv_unlock_avformat();
623         return ret;
624     }
625
626     avpriv_unlock_avformat();
627     return 0;
628 }
629
630 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
631 {
632     AviSynthContext *avs = s->priv_data;
633     AVStream *st;
634     int discard = 0;
635     int ret;
636
637     if (avs->error)
638         return AVERROR_UNKNOWN;
639
640     /* If either stream reaches EOF, try to read the other one before
641      * giving up. */
642     avisynth_next_stream(s, &st, pkt, &discard);
643     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
644         ret = avisynth_read_packet_video(s, pkt, discard);
645         if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
646             avisynth_next_stream(s, &st, pkt, &discard);
647             return avisynth_read_packet_audio(s, pkt, discard);
648         }
649     } else {
650         ret = avisynth_read_packet_audio(s, pkt, discard);
651         if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
652             avisynth_next_stream(s, &st, pkt, &discard);
653             return avisynth_read_packet_video(s, pkt, discard);
654         }
655     }
656
657     return ret;
658 }
659
660 static av_cold int avisynth_read_close(AVFormatContext *s)
661 {
662     if (avpriv_lock_avformat())
663         return AVERROR_UNKNOWN;
664
665     avisynth_context_destroy(s->priv_data);
666     avpriv_unlock_avformat();
667     return 0;
668 }
669
670 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
671                               int64_t timestamp, int flags)
672 {
673     AviSynthContext *avs = s->priv_data;
674     AVStream *st;
675     AVRational fps, samplerate;
676
677     if (avs->error)
678         return AVERROR_UNKNOWN;
679
680     fps        = (AVRational) { avs->vi->fps_numerator,
681                                 avs->vi->fps_denominator };
682     samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
683
684     st = s->streams[stream_index];
685     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
686         /* AviSynth frame counts are signed int. */
687         if ((timestamp >= avs->vi->num_frames) ||
688             (timestamp > INT_MAX)              ||
689             (timestamp < 0))
690             return AVERROR_EOF;
691         avs->curr_frame = timestamp;
692         if (avs_has_audio(avs->vi))
693             avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
694     } else {
695         if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
696             return AVERROR_EOF;
697         /* Force frame granularity for seeking. */
698         if (avs_has_video(avs->vi)) {
699             avs->curr_frame  = av_rescale_q(timestamp, fps, samplerate);
700             avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
701         } else {
702             avs->curr_sample = timestamp;
703         }
704     }
705
706     return 0;
707 }
708
709 AVInputFormat ff_avisynth_demuxer = {
710     .name           = "avisynth",
711     .long_name      = NULL_IF_CONFIG_SMALL("AviSynth script"),
712     .priv_data_size = sizeof(AviSynthContext),
713     .read_header    = avisynth_read_header,
714     .read_packet    = avisynth_read_packet,
715     .read_close     = avisynth_read_close,
716     .read_seek      = avisynth_read_seek,
717     .extensions     = "avs",
718 };