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