libavformat/avisynth.c
9dc5607b
 /*
f0b234ab
  * AviSynth/AvxSynth support
b9ad0094
  * Copyright (c) 2012 AvxSynth Team.
b78e7197
  *
b9ad0094
  * This file is part of FFmpeg
b78e7197
  * FFmpeg is free software; you can redistribute it and/or
9dc5607b
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
9dc5607b
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
9dc5607b
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
9dc5607b
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
97b052e5
 #include "libavutil/internal.h"
2c18bfe6
 #include "libavcodec/internal.h"
9dc5607b
 #include "avformat.h"
c3f9ebf7
 #include "internal.h"
b9ad0094
 
1549122d
 /* Enable function pointer definitions for runtime loading. */
b9ad0094
 #define AVSC_NO_DECLSPEC
 
1549122d
 /* Platform-specific directives for AviSynth vs AvxSynth. */
b9ad0094
 #ifdef _WIN32
   #include <windows.h>
   #undef EXTERN_C
   #include "compat/avisynth/avisynth_c.h"
2c25e83b
   #include "compat/avisynth/avisynth_c_25.h"
b9ad0094
   #define AVISYNTH_LIB "avisynth"
bd97ba72
   #define USING_AVISYNTH
b9ad0094
 #else
   #include <dlfcn.h>
   #include "compat/avisynth/avxsynth_c.h"
2c18bfe6
     #if defined (__APPLE__)
       #define AVISYNTH_LIB "libavxsynth.dylib"
     #else
       #define AVISYNTH_LIB "libavxsynth.so"
     #endif
b9ad0094
 
   #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
   #define GetProcAddress dlsym
   #define FreeLibrary dlclose
 #endif
9dc5607b
 
da985267
 typedef struct AviSynthLibrary {
b9ad0094
     void *library;
2c18bfe6
 #define AVSC_DECLARE_FUNC(name) name ## _func name
f277d6bf
     AVSC_DECLARE_FUNC(avs_bit_blt);
     AVSC_DECLARE_FUNC(avs_clip_get_error);
b9ad0094
     AVSC_DECLARE_FUNC(avs_create_script_environment);
     AVSC_DECLARE_FUNC(avs_delete_script_environment);
f277d6bf
     AVSC_DECLARE_FUNC(avs_get_audio);
b9ad0094
     AVSC_DECLARE_FUNC(avs_get_error);
f277d6bf
     AVSC_DECLARE_FUNC(avs_get_frame);
9db353bc
     AVSC_DECLARE_FUNC(avs_get_version);
b9ad0094
     AVSC_DECLARE_FUNC(avs_get_video_info);
f277d6bf
     AVSC_DECLARE_FUNC(avs_invoke);
b9ad0094
     AVSC_DECLARE_FUNC(avs_release_clip);
f277d6bf
     AVSC_DECLARE_FUNC(avs_release_value);
b9ad0094
     AVSC_DECLARE_FUNC(avs_release_video_frame);
f277d6bf
     AVSC_DECLARE_FUNC(avs_take_clip);
b9ad0094
 #undef AVSC_DECLARE_FUNC
 } AviSynthLibrary;
 
da985267
 typedef struct AviSynthContext {
b9ad0094
     AVS_ScriptEnvironment *env;
     AVS_Clip *clip;
     const AVS_VideoInfo *vi;
 
1549122d
     /* avisynth_read_packet_video() iterates over this. */
b9ad0094
     int n_planes;
     const int *planes;
 
     int curr_stream;
     int curr_frame;
     int64_t curr_sample;
 
     int error;
 
1549122d
     /* Linked list pointers. */
b9ad0094
     struct AviSynthContext *next;
da985267
 } AviSynthContext;
9dc5607b
 
2c18bfe6
 static const int avs_planes_packed[1] = { 0 };
 static const int avs_planes_grey[1]   = { AVS_PLANAR_Y };
 static const int avs_planes_yuv[3]    = { AVS_PLANAR_Y, AVS_PLANAR_U,
                                           AVS_PLANAR_V };
b9ad0094
 
1549122d
 /* A conflict between C++ global objects, atexit, and dynamic loading requires
  * us to register our own atexit handler to prevent double freeing. */
c46ab34d
 static AviSynthLibrary avs_library;
2c18bfe6
 static int avs_atexit_called        = 0;
b9ad0094
 
1549122d
 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
b9ad0094
 static AviSynthContext *avs_ctx_list = NULL;
 
 static av_cold void avisynth_atexit_handler(void);
 
2c18bfe6
 static av_cold int avisynth_load_library(void)
 {
c46ab34d
     avs_library.library = LoadLibrary(AVISYNTH_LIB);
     if (!avs_library.library)
b9ad0094
         return AVERROR_UNKNOWN;
 
c46ab34d
 #define LOAD_AVS_FUNC(name, continue_on_fail)                          \
         avs_library.name =                                             \
             (void *)GetProcAddress(avs_library.library, #name);        \
         if (!continue_on_fail && !avs_library.name)                    \
2c18bfe6
             goto fail;
 
f277d6bf
     LOAD_AVS_FUNC(avs_bit_blt, 0);
     LOAD_AVS_FUNC(avs_clip_get_error, 0);
b9ad0094
     LOAD_AVS_FUNC(avs_create_script_environment, 0);
     LOAD_AVS_FUNC(avs_delete_script_environment, 0);
f277d6bf
     LOAD_AVS_FUNC(avs_get_audio, 0);
b9ad0094
     LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
f277d6bf
     LOAD_AVS_FUNC(avs_get_frame, 0);
9db353bc
     LOAD_AVS_FUNC(avs_get_version, 0);
b9ad0094
     LOAD_AVS_FUNC(avs_get_video_info, 0);
f277d6bf
     LOAD_AVS_FUNC(avs_invoke, 0);
b9ad0094
     LOAD_AVS_FUNC(avs_release_clip, 0);
f277d6bf
     LOAD_AVS_FUNC(avs_release_value, 0);
b9ad0094
     LOAD_AVS_FUNC(avs_release_video_frame, 0);
f277d6bf
     LOAD_AVS_FUNC(avs_take_clip, 0);
b9ad0094
 #undef LOAD_AVS_FUNC
 
     atexit(avisynth_atexit_handler);
     return 0;
 
 fail:
c46ab34d
     FreeLibrary(avs_library.library);
b9ad0094
     return AVERROR_UNKNOWN;
 }
 
1549122d
 /* Note that avisynth_context_create and avisynth_context_destroy
  * do not allocate or free the actual context! That is taken care of
  * by libavformat. */
2c18bfe6
 static av_cold int avisynth_context_create(AVFormatContext *s)
 {
df6279e7
     AviSynthContext *avs = s->priv_data;
b9ad0094
     int ret;
 
c46ab34d
     if (!avs_library.library)
b9ad0094
         if (ret = avisynth_load_library())
             return ret;
 
c46ab34d
     avs->env = avs_library.avs_create_script_environment(3);
     if (avs_library.avs_get_error) {
         const char *error = avs_library.avs_get_error(avs->env);
b9ad0094
         if (error) {
             av_log(s, AV_LOG_ERROR, "%s\n", error);
             return AVERROR_UNKNOWN;
9dc5607b
         }
     }
 
444001bd
     if (!avs_ctx_list) {
         avs_ctx_list = avs;
     } else {
2c18bfe6
         avs->next    = avs_ctx_list;
444001bd
         avs_ctx_list = avs;
     }
 
b9ad0094
     return 0;
9dc5607b
 }
 
2c18bfe6
 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
 {
b9ad0094
     if (avs_atexit_called)
2c18bfe6
         return;
b9ad0094
 
     if (avs == avs_ctx_list) {
         avs_ctx_list = avs->next;
     } else {
         AviSynthContext *prev = avs_ctx_list;
         while (prev->next != avs)
             prev = prev->next;
         prev->next = avs->next;
     }
9dc5607b
 
b9ad0094
     if (avs->clip) {
c46ab34d
         avs_library.avs_release_clip(avs->clip);
b9ad0094
         avs->clip = NULL;
     }
     if (avs->env) {
c46ab34d
         avs_library.avs_delete_script_environment(avs->env);
b9ad0094
         avs->env = NULL;
     }
 }
9dc5607b
 
2c18bfe6
 static av_cold void avisynth_atexit_handler(void)
 {
b9ad0094
     AviSynthContext *avs = avs_ctx_list;
9dc5607b
 
b9ad0094
     while (avs) {
         AviSynthContext *next = avs->next;
         avisynth_context_destroy(avs);
         avs = next;
     }
c46ab34d
     FreeLibrary(avs_library.library);
9dc5607b
 
b9ad0094
     avs_atexit_called = 1;
 }
9dc5607b
 
1549122d
 /* Create AVStream from audio and video data. */
2c18bfe6
 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     int planar = 0; // 0: packed, 1: YUV, 2: Y8
 
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
c7f9aab8
     st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
2c18bfe6
     st->codec->width      = avs->vi->width;
     st->codec->height     = avs->vi->height;
 
     st->time_base         = (AVRational) { avs->vi->fps_denominator,
                                            avs->vi->fps_numerator };
     st->avg_frame_rate    = (AVRational) { avs->vi->fps_numerator,
                                            avs->vi->fps_denominator };
     st->start_time        = 0;
     st->duration          = avs->vi->num_frames;
     st->nb_frames         = avs->vi->num_frames;
b9ad0094
 
     switch (avs->vi->pixel_type) {
bd97ba72
 #ifdef USING_AVISYNTH
b9ad0094
     case AVS_CS_YV24:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUV444P;
2c18bfe6
         planar             = 1;
b9ad0094
         break;
     case AVS_CS_YV16:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUV422P;
2c18bfe6
         planar             = 1;
b9ad0094
         break;
     case AVS_CS_YV411:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUV411P;
2c18bfe6
         planar             = 1;
b9ad0094
         break;
     case AVS_CS_Y8:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_GRAY8;
2c18bfe6
         planar             = 2;
b9ad0094
         break;
 #endif
     case AVS_CS_BGR24:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_BGR24;
b9ad0094
         break;
     case AVS_CS_BGR32:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_RGB32;
b9ad0094
         break;
     case AVS_CS_YUY2:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUYV422;
b9ad0094
         break;
     case AVS_CS_YV12:
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
2c18bfe6
         planar             = 1;
b9ad0094
         break;
     case AVS_CS_I420: // Is this even used anywhere?
d64f3b72
         st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
2c18bfe6
         planar             = 1;
b9ad0094
         break;
     default:
2c18bfe6
         av_log(s, AV_LOG_ERROR,
                "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
b9ad0094
         avs->error = 1;
         return AVERROR_UNKNOWN;
     }
9dc5607b
 
b9ad0094
     switch (planar) {
     case 2: // Y8
         avs->n_planes = 1;
2c18bfe6
         avs->planes   = avs_planes_grey;
b9ad0094
         break;
     case 1: // YUV
         avs->n_planes = 3;
2c18bfe6
         avs->planes   = avs_planes_yuv;
b9ad0094
         break;
     default:
         avs->n_planes = 1;
2c18bfe6
         avs->planes   = avs_planes_packed;
b9ad0094
     }
     return 0;
 }
9dc5607b
 
2c18bfe6
 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
 
2c18bfe6
     st->codec->codec_type  = AVMEDIA_TYPE_AUDIO;
b9ad0094
     st->codec->sample_rate = avs->vi->audio_samples_per_second;
2c18bfe6
     st->codec->channels    = avs->vi->nchannels;
     st->time_base          = (AVRational) { 1,
                                             avs->vi->audio_samples_per_second };
b9ad0094
 
     switch (avs->vi->sample_type) {
     case AVS_SAMPLE_INT8:
c7f9aab8
         st->codec->codec_id = AV_CODEC_ID_PCM_U8;
b9ad0094
         break;
     case AVS_SAMPLE_INT16:
c7f9aab8
         st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
b9ad0094
         break;
     case AVS_SAMPLE_INT24:
c7f9aab8
         st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
b9ad0094
         break;
     case AVS_SAMPLE_INT32:
c7f9aab8
         st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
b9ad0094
         break;
     case AVS_SAMPLE_FLOAT:
c7f9aab8
         st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
b9ad0094
         break;
     default:
2c18bfe6
         av_log(s, AV_LOG_ERROR,
                "unknown AviSynth sample type %d\n", avs->vi->sample_type);
b9ad0094
         avs->error = 1;
         return AVERROR_UNKNOWN;
     }
     return 0;
 }
9dc5607b
 
2c18bfe6
 static int avisynth_create_stream(AVFormatContext *s)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     AVStream *st;
     int ret;
     int id = 0;
 
     if (avs_has_video(avs->vi)) {
         st = avformat_new_stream(s, NULL);
         if (!st)
             return AVERROR_UNKNOWN;
         st->id = id++;
         if (ret = avisynth_create_stream_video(s, st))
             return ret;
     }
     if (avs_has_audio(avs->vi)) {
         st = avformat_new_stream(s, NULL);
         if (!st)
             return AVERROR_UNKNOWN;
         st->id = id++;
         if (ret = avisynth_create_stream_audio(s, st))
             return ret;
     }
     return 0;
9dc5607b
 }
 
2c18bfe6
 static int avisynth_open_file(AVFormatContext *s)
 {
df6279e7
     AviSynthContext *avs = s->priv_data;
b9ad0094
     AVS_Value arg, val;
     int ret;
bd97ba72
 #ifdef USING_AVISYNTH
81c5ceed
     char filename_ansi[MAX_PATH * 4];
     wchar_t filename_wc[MAX_PATH * 4];
 #endif
b9ad0094
 
     if (ret = avisynth_context_create(s))
         return ret;
9dc5607b
 
bd97ba72
 #ifdef USING_AVISYNTH
1549122d
     /* Convert UTF-8 to ANSI code page */
81c5ceed
     MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
2c18bfe6
     WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
                         MAX_PATH * 4, NULL, NULL);
81c5ceed
     arg = avs_new_value_string(filename_ansi);
 #else
b9ad0094
     arg = avs_new_value_string(s->filename);
81c5ceed
 #endif
c46ab34d
     val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
b9ad0094
     if (avs_is_error(val)) {
         av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
         ret = AVERROR_UNKNOWN;
         goto fail;
9dc5607b
     }
b9ad0094
     if (!avs_is_clip(val)) {
8d55362f
         av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
b9ad0094
         ret = AVERROR_UNKNOWN;
         goto fail;
     }
 
c46ab34d
     avs->clip = avs_library.avs_take_clip(val, avs->env);
     avs->vi   = avs_library.avs_get_video_info(avs->clip);
b9ad0094
 
1549122d
     /* Release the AVS_Value as it will go out of scope. */
c46ab34d
     avs_library.avs_release_value(val);
b9ad0094
 
     if (ret = avisynth_create_stream(s))
         goto fail;
 
     return 0;
9dc5607b
 
b9ad0094
 fail:
     avisynth_context_destroy(avs);
     return ret;
9dc5607b
 }
 
2c18bfe6
 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
                                  AVPacket *pkt, int *discard)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
9dc5607b
 
4cb9c201
     avs->curr_stream++;
b9ad0094
     avs->curr_stream %= s->nb_streams;
 
4cb9c201
     *st = s->streams[avs->curr_stream];
b9ad0094
     if ((*st)->discard == AVDISCARD_ALL)
         *discard = 1;
     else
         *discard = 0;
 
     return;
 }
 
1549122d
 /* Copy AviSynth clip data into an AVPacket. */
2c18bfe6
 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
                                       int discard)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     AVS_VideoFrame *frame;
685617ac
     unsigned char *dst_p;
     const unsigned char *src_p;
4cb9c201
     int n, i, plane, rowsize, planeheight, pitch, bits;
685617ac
     const char *error;
b9ad0094
 
     if (avs->curr_frame >= avs->vi->num_frames)
         return AVERROR_EOF;
 
1549122d
     /* This must happen even if the stream is discarded to prevent desync. */
ca3cef71
     n = avs->curr_frame++;
b9ad0094
     if (discard)
         return 0;
 
d10d60be
 #ifdef USING_AVISYNTH
     /* Define the bpp values for the new AviSynth 2.6 colorspaces.
      * Since AvxSynth doesn't have these functions, special-case
      * it in order to avoid implicit declaration errors. */
 
2c18bfe6
     if (avs_is_yv24(avs->vi))
b9ad0094
         bits = 24;
2c18bfe6
     else if (avs_is_yv16(avs->vi))
b9ad0094
         bits = 16;
2c18bfe6
     else if (avs_is_yv411(avs->vi))
b9ad0094
         bits = 12;
2c18bfe6
     else if (avs_is_y8(avs->vi))
b9ad0094
         bits = 8;
2c18bfe6
     else
d10d60be
 #endif
b9ad0094
         bits = avs_bits_per_pixel(avs->vi);
 
1549122d
     /* Without the cast to int64_t, calculation overflows at about 9k x 9k
      * resolution. */
2c18bfe6
     pkt->size = (((int64_t)avs->vi->width *
                   (int64_t)avs->vi->height) * bits) / 8;
b9ad0094
     if (!pkt->size)
         return AVERROR_UNKNOWN;
02dd178d
 
4cb9c201
     if (av_new_packet(pkt, pkt->size) < 0)
7ac67583
         return AVERROR(ENOMEM);
b9ad0094
 
4cb9c201
     pkt->pts      = n;
     pkt->dts      = n;
     pkt->duration = 1;
     pkt->stream_index = avs->curr_stream;
16ae337b
 
c46ab34d
     frame = avs_library.avs_get_frame(avs->clip, n);
     error = avs_library.avs_clip_get_error(avs->clip);
b9ad0094
     if (error) {
         av_log(s, AV_LOG_ERROR, "%s\n", error);
         avs->error = 1;
02dd178d
         av_packet_unref(pkt);
b9ad0094
         return AVERROR_UNKNOWN;
     }
 
     dst_p = pkt->data;
     for (i = 0; i < avs->n_planes; i++) {
         plane = avs->planes[i];
         src_p = avs_get_read_ptr_p(frame, plane);
2c25e83b
         pitch = avs_get_pitch_p(frame, plane);
 
bd97ba72
 #ifdef USING_AVISYNTH
c46ab34d
         if (avs_library.avs_get_version(avs->clip) == 3) {
2c18bfe6
             rowsize     = avs_get_row_size_p_25(frame, plane);
2c25e83b
             planeheight = avs_get_height_p_25(frame, plane);
         } else {
2c18bfe6
             rowsize     = avs_get_row_size_p(frame, plane);
2c25e83b
             planeheight = avs_get_height_p(frame, plane);
         }
 #else
2c18bfe6
         rowsize     = avs_get_row_size_p(frame, plane);
b9ad0094
         planeheight = avs_get_height_p(frame, plane);
2c25e83b
 #endif
b9ad0094
 
1549122d
         /* Flip RGB video. */
b9ad0094
         if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
             src_p = src_p + (planeheight - 1) * pitch;
             pitch = -pitch;
         }
 
c46ab34d
         avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
2c18bfe6
                                  rowsize, planeheight);
b9ad0094
         dst_p += rowsize * planeheight;
     }
 
c46ab34d
     avs_library.avs_release_video_frame(frame);
b9ad0094
     return 0;
 }
 
2c18bfe6
 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
                                       int discard)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     AVRational fps, samplerate;
4cb9c201
     int samples;
ca3cef71
     int64_t n;
685617ac
     const char *error;
b9ad0094
 
     if (avs->curr_sample >= avs->vi->num_audio_samples)
         return AVERROR_EOF;
 
2c18bfe6
     fps.num        = avs->vi->fps_numerator;
     fps.den        = avs->vi->fps_denominator;
b9ad0094
     samplerate.num = avs->vi->audio_samples_per_second;
     samplerate.den = 1;
 
     if (avs_has_video(avs->vi)) {
         if (avs->curr_frame < avs->vi->num_frames)
2c18bfe6
             samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
                       avs->curr_sample;
b9ad0094
         else
             samples = av_rescale_q(1, samplerate, fps);
     } else {
         samples = 1000;
     }
 
1549122d
     /* After seeking, audio may catch up with video. */
b9ad0094
     if (samples <= 0) {
         pkt->size = 0;
         pkt->data = NULL;
         return 0;
     }
 
     if (avs->curr_sample + samples > avs->vi->num_audio_samples)
         samples = avs->vi->num_audio_samples - avs->curr_sample;
 
1549122d
     /* This must happen even if the stream is discarded to prevent desync. */
2c18bfe6
     n                 = avs->curr_sample;
b9ad0094
     avs->curr_sample += samples;
     if (discard)
         return 0;
 
2c18bfe6
     pkt->size = avs_bytes_per_channel_sample(avs->vi) *
                 samples * avs->vi->nchannels;
b9ad0094
     if (!pkt->size)
         return AVERROR_UNKNOWN;
02dd178d
 
4cb9c201
     if (av_new_packet(pkt, pkt->size) < 0)
7ac67583
         return AVERROR(ENOMEM);
b9ad0094
 
4cb9c201
     pkt->pts      = n;
     pkt->dts      = n;
     pkt->duration = samples;
     pkt->stream_index = avs->curr_stream;
16ae337b
 
c46ab34d
     avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
     error = avs_library.avs_clip_get_error(avs->clip);
b9ad0094
     if (error) {
         av_log(s, AV_LOG_ERROR, "%s\n", error);
         avs->error = 1;
02dd178d
         av_packet_unref(pkt);
b9ad0094
         return AVERROR_UNKNOWN;
     }
     return 0;
 }
 
2c18bfe6
 static av_cold int avisynth_read_header(AVFormatContext *s)
 {
b9ad0094
     int ret;
 
     // Calling library must implement a lock for thread-safe opens.
     if (ret = avpriv_lock_avformat())
         return ret;
 
     if (ret = avisynth_open_file(s)) {
         avpriv_unlock_avformat();
         return ret;
     }
 
     avpriv_unlock_avformat();
     return 0;
 }
 
2c18bfe6
 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     AVStream *st;
     int discard = 0;
     int ret;
 
     if (avs->error)
         return AVERROR_UNKNOWN;
 
1549122d
     /* If either stream reaches EOF, try to read the other one before
      * giving up. */
b9ad0094
     avisynth_next_stream(s, &st, pkt, &discard);
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
         ret = avisynth_read_packet_video(s, pkt, discard);
         if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
             avisynth_next_stream(s, &st, pkt, &discard);
             return avisynth_read_packet_audio(s, pkt, discard);
         }
     } else {
         ret = avisynth_read_packet_audio(s, pkt, discard);
         if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
             avisynth_next_stream(s, &st, pkt, &discard);
             return avisynth_read_packet_video(s, pkt, discard);
         }
     }
f87a2e12
 
     return ret;
b9ad0094
 }
 
2c18bfe6
 static av_cold int avisynth_read_close(AVFormatContext *s)
 {
b9ad0094
     if (avpriv_lock_avformat())
         return AVERROR_UNKNOWN;
 
     avisynth_context_destroy(s->priv_data);
     avpriv_unlock_avformat();
     return 0;
 }
 
2c18bfe6
 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
                               int64_t timestamp, int flags)
 {
b9ad0094
     AviSynthContext *avs = s->priv_data;
     AVStream *st;
     AVRational fps, samplerate;
 
     if (avs->error)
         return AVERROR_UNKNOWN;
 
2c18bfe6
     fps        = (AVRational) { avs->vi->fps_numerator,
                                 avs->vi->fps_denominator };
     samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
b9ad0094
 
     st = s->streams[stream_index];
     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1549122d
         /* AviSynth frame counts are signed int. */
2c18bfe6
         if ((timestamp >= avs->vi->num_frames) ||
             (timestamp > INT_MAX)              ||
             (timestamp < 0))
b9ad0094
             return AVERROR_EOF;
         avs->curr_frame = timestamp;
         if (avs_has_audio(avs->vi))
             avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
     } else {
         if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
             return AVERROR_EOF;
1549122d
         /* Force frame granularity for seeking. */
b9ad0094
         if (avs_has_video(avs->vi)) {
2c18bfe6
             avs->curr_frame  = av_rescale_q(timestamp, fps, samplerate);
b9ad0094
             avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
         } else {
             avs->curr_sample = timestamp;
         }
9dc5607b
     }
 
b9ad0094
     return 0;
9dc5607b
 }
 
66355be3
 AVInputFormat ff_avisynth_demuxer = {
0f5b0b41
     .name           = "avisynth",
b9ad0094
     .long_name      = NULL_IF_CONFIG_SMALL("AviSynth script"),
     .priv_data_size = sizeof(AviSynthContext),
dfc2c4d9
     .read_header    = avisynth_read_header,
     .read_packet    = avisynth_read_packet,
     .read_close     = avisynth_read_close,
     .read_seek      = avisynth_read_seek,
     .extensions     = "avs",
9dc5607b
 };