Skip to content
Snippets Groups Projects
avisynth.c 26.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • d s's avatar
    d s committed
     * AviSynth/AvxSynth support
    
     * Copyright (c) 2012 AvxSynth Team
    
    d s's avatar
    d s committed
     * This file is part of FFmpeg
    
     * FFmpeg is free software; you can redistribute it and/or
    
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
    
     * version 2.1 of the License, or (at your option) any later version.
    
     * FFmpeg is distributed in the hope that it will be useful,
    
     * 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
    
     * License along with FFmpeg; if not, write to the Free Software
    
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
     */
    
    
    #include "libavutil/internal.h"
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    #include "libavcodec/internal.h"
    
    #include "internal.h"
    
    d s's avatar
    d s committed
    
    
    /* Enable function pointer definitions for runtime loading. */
    
    d s's avatar
    d s committed
    #define AVSC_NO_DECLSPEC
    
    
    /* Platform-specific directives for AviSynth vs AvxSynth. */
    
    d s's avatar
    d s committed
    #ifdef _WIN32
      #include <windows.h>
      #undef EXTERN_C
      #include "compat/avisynth/avisynth_c.h"
      #define AVISYNTH_LIB "avisynth"
    
      #define USING_AVISYNTH
    
    d s's avatar
    d s committed
    #else
      #include <dlfcn.h>
      #include "compat/avisynth/avxsynth_c.h"
    
      #define AVISYNTH_NAME "libavxsynth"
      #define AVISYNTH_LIB AVISYNTH_NAME SLIBSUF
    
    d s's avatar
    d s committed
    
    
      #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_LOCAL)
    
    d s's avatar
    d s committed
      #define GetProcAddress dlsym
      #define FreeLibrary dlclose
    #endif
    
    typedef struct AviSynthLibrary {
    
    d s's avatar
    d s committed
        void *library;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    #define AVSC_DECLARE_FUNC(name) name ## _func name
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_bit_blt);
        AVSC_DECLARE_FUNC(avs_clip_get_error);
    
    d s's avatar
    d s committed
        AVSC_DECLARE_FUNC(avs_create_script_environment);
        AVSC_DECLARE_FUNC(avs_delete_script_environment);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_get_audio);
    
    d s's avatar
    d s committed
        AVSC_DECLARE_FUNC(avs_get_error);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_get_frame);
    
        AVSC_DECLARE_FUNC(avs_get_version);
    
    d s's avatar
    d s committed
        AVSC_DECLARE_FUNC(avs_get_video_info);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_invoke);
    
    d s's avatar
    d s committed
        AVSC_DECLARE_FUNC(avs_release_clip);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_release_value);
    
    d s's avatar
    d s committed
        AVSC_DECLARE_FUNC(avs_release_video_frame);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        AVSC_DECLARE_FUNC(avs_take_clip);
    
    #ifdef USING_AVISYNTH
        AVSC_DECLARE_FUNC(avs_bits_per_pixel);
        AVSC_DECLARE_FUNC(avs_get_height_p);
        AVSC_DECLARE_FUNC(avs_get_pitch_p);
        AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
        AVSC_DECLARE_FUNC(avs_get_row_size_p);
    
        AVSC_DECLARE_FUNC(avs_is_planar_rgb);
        AVSC_DECLARE_FUNC(avs_is_planar_rgba);
    
    d s's avatar
    d s committed
    #undef AVSC_DECLARE_FUNC
    } AviSynthLibrary;
    
    
    typedef struct AviSynthContext {
    
    d s's avatar
    d s committed
        AVS_ScriptEnvironment *env;
        AVS_Clip *clip;
        const AVS_VideoInfo *vi;
    
    
        /* avisynth_read_packet_video() iterates over this. */
    
    d s's avatar
    d s committed
        int n_planes;
        const int *planes;
    
        int curr_stream;
        int curr_frame;
        int64_t curr_sample;
    
        int error;
    
    
        /* Linked list pointers. */
    
    d s's avatar
    d s committed
        struct AviSynthContext *next;
    
    } AviSynthContext;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    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 };
    
    #ifdef USING_AVISYNTH
    static const int avs_planes_rgb[3]    = { AVS_PLANAR_G, AVS_PLANAR_B,
                                              AVS_PLANAR_R };
    static const int avs_planes_yuva[4]   = { AVS_PLANAR_Y, AVS_PLANAR_U,
                                              AVS_PLANAR_V, AVS_PLANAR_A };
    static const int avs_planes_rgba[4]   = { AVS_PLANAR_G, AVS_PLANAR_B,
                                              AVS_PLANAR_R, AVS_PLANAR_A };
    #endif
    
    d s's avatar
    d s committed
    
    
    /* A conflict between C++ global objects, atexit, and dynamic loading requires
     * us to register our own atexit handler to prevent double freeing. */
    
    static AviSynthLibrary avs_library;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avs_atexit_called        = 0;
    
    d s's avatar
    d s committed
    
    
    /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
    
    d s's avatar
    d s committed
    static AviSynthContext *avs_ctx_list = NULL;
    
    static av_cold void avisynth_atexit_handler(void);
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold int avisynth_load_library(void)
    {
    
        avs_library.library = LoadLibrary(AVISYNTH_LIB);
        if (!avs_library.library)
    
    d s's avatar
    d s committed
            return AVERROR_UNKNOWN;
    
    
    #define LOAD_AVS_FUNC(name, continue_on_fail)                          \
            avs_library.name =                                             \
                (void *)GetProcAddress(avs_library.library, #name);        \
            if (!continue_on_fail && !avs_library.name)                    \
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
                goto fail;
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_bit_blt, 0);
        LOAD_AVS_FUNC(avs_clip_get_error, 0);
    
    d s's avatar
    d s committed
        LOAD_AVS_FUNC(avs_create_script_environment, 0);
        LOAD_AVS_FUNC(avs_delete_script_environment, 0);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_get_audio, 0);
    
    d s's avatar
    d s committed
        LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_get_frame, 0);
    
        LOAD_AVS_FUNC(avs_get_version, 0);
    
    d s's avatar
    d s committed
        LOAD_AVS_FUNC(avs_get_video_info, 0);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_invoke, 0);
    
    d s's avatar
    d s committed
        LOAD_AVS_FUNC(avs_release_clip, 0);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_release_value, 0);
    
    d s's avatar
    d s committed
        LOAD_AVS_FUNC(avs_release_video_frame, 0);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        LOAD_AVS_FUNC(avs_take_clip, 0);
    
        LOAD_AVS_FUNC(avs_bits_per_pixel, 1);
        LOAD_AVS_FUNC(avs_get_height_p, 1);
        LOAD_AVS_FUNC(avs_get_pitch_p, 1);
        LOAD_AVS_FUNC(avs_get_read_ptr_p, 1);
        LOAD_AVS_FUNC(avs_get_row_size_p, 1);
    
        LOAD_AVS_FUNC(avs_is_planar_rgb, 1);
        LOAD_AVS_FUNC(avs_is_planar_rgba, 1);
    
    d s's avatar
    d s committed
    #undef LOAD_AVS_FUNC
    
        atexit(avisynth_atexit_handler);
        return 0;
    
    fail:
    
        FreeLibrary(avs_library.library);
    
    d s's avatar
    d s committed
        return AVERROR_UNKNOWN;
    }
    
    
    /* Note that avisynth_context_create and avisynth_context_destroy
     * do not allocate or free the actual context! That is taken care of
     * by libavformat. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold int avisynth_context_create(AVFormatContext *s)
    {
    
        AviSynthContext *avs = s->priv_data;
    
    d s's avatar
    d s committed
        int ret;
    
    
        if (!avs_library.library)
    
    d s's avatar
    d s committed
            if (ret = avisynth_load_library())
                return ret;
    
    
        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);
    
    d s's avatar
    d s committed
            if (error) {
                av_log(s, AV_LOG_ERROR, "%s\n", error);
                return AVERROR_UNKNOWN;
    
        if (!avs_ctx_list) {
            avs_ctx_list = avs;
        } else {
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            avs->next    = avs_ctx_list;
    
    d s's avatar
    d s committed
        return 0;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold void avisynth_context_destroy(AviSynthContext *avs)
    {
    
    d s's avatar
    d s committed
        if (avs_atexit_called)
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            return;
    
    d s's avatar
    d s committed
    
        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;
        }
    
    d s's avatar
    d s committed
        if (avs->clip) {
    
            avs_library.avs_release_clip(avs->clip);
    
    d s's avatar
    d s committed
            avs->clip = NULL;
        }
        if (avs->env) {
    
            avs_library.avs_delete_script_environment(avs->env);
    
    d s's avatar
    d s committed
            avs->env = NULL;
        }
    }
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold void avisynth_atexit_handler(void)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = avs_ctx_list;
    
    d s's avatar
    d s committed
        while (avs) {
            AviSynthContext *next = avs->next;
            avisynth_context_destroy(avs);
            avs = next;
        }
    
        FreeLibrary(avs_library.library);
    
    d s's avatar
    d s committed
        avs_atexit_called = 1;
    }
    
    /* Create AVStream from audio and video data. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
    
        int planar = 0; // 0: packed, 1: YUV, 2: Y8, 3: Planar RGB, 4: YUVA, 5: Planar RGBA
    
    d s's avatar
    d s committed
    
    
        st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
        st->codecpar->codec_id   = AV_CODEC_ID_RAWVIDEO;
        st->codecpar->width      = avs->vi->width;
        st->codecpar->height     = avs->vi->height;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    
        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;
    
        avpriv_set_pts_info(st, 32, avs->vi->fps_denominator, avs->vi->fps_numerator);
    
    d s's avatar
    d s committed
    
        switch (avs->vi->pixel_type) {
    
    #ifdef USING_AVISYNTH
    
    /* 10~16-bit YUV pix_fmts (AviSynth+) */
        case AVS_CS_YUV444P10:
            st->codecpar->format = AV_PIX_FMT_YUV444P10;
            planar               = 1;
            break;
        case AVS_CS_YUV422P10:
            st->codecpar->format = AV_PIX_FMT_YUV422P10;
            planar               = 1;
            break;
        case AVS_CS_YUV420P10:
            st->codecpar->format = AV_PIX_FMT_YUV420P10;
            planar               = 1;
            break;
        case AVS_CS_YUV444P12:
            st->codecpar->format = AV_PIX_FMT_YUV444P12;
            planar               = 1;
            break;
        case AVS_CS_YUV422P12:
            st->codecpar->format = AV_PIX_FMT_YUV422P12;
            planar               = 1;
            break;
        case AVS_CS_YUV420P12:
            st->codecpar->format = AV_PIX_FMT_YUV420P12;
            planar               = 1;
            break;
        case AVS_CS_YUV444P14:
            st->codecpar->format = AV_PIX_FMT_YUV444P14;
            planar               = 1;
            break;
        case AVS_CS_YUV422P14:
            st->codecpar->format = AV_PIX_FMT_YUV422P14;
            planar               = 1;
            break;
        case AVS_CS_YUV420P14:
            st->codecpar->format = AV_PIX_FMT_YUV420P14;
            planar               = 1;
            break;
        case AVS_CS_YUV444P16:
            st->codecpar->format = AV_PIX_FMT_YUV444P16;
            planar               = 1;
            break;
        case AVS_CS_YUV422P16:
            st->codecpar->format = AV_PIX_FMT_YUV422P16;
            planar               = 1;
            break;
        case AVS_CS_YUV420P16:
            st->codecpar->format = AV_PIX_FMT_YUV420P16;
            planar               = 1;
            break;
    /* 8~16-bit YUV pix_fmts with Alpha (AviSynth+) */
        case AVS_CS_YUVA444:
            st->codecpar->format = AV_PIX_FMT_YUVA444P;
            planar               = 4;
            break;
        case AVS_CS_YUVA422:
            st->codecpar->format = AV_PIX_FMT_YUVA422P;
            planar               = 4;
            break;
        case AVS_CS_YUVA420:
            st->codecpar->format = AV_PIX_FMT_YUVA420P;
            planar               = 4;
            break;
        case AVS_CS_YUVA444P10:
            st->codecpar->format = AV_PIX_FMT_YUVA444P10;
            planar               = 4;
            break;
        case AVS_CS_YUVA422P10:
            st->codecpar->format = AV_PIX_FMT_YUVA422P10;
            planar               = 4;
            break;
        case AVS_CS_YUVA420P10:
            st->codecpar->format = AV_PIX_FMT_YUVA420P10;
            planar               = 4;
            break;
        case AVS_CS_YUVA444P16:
            st->codecpar->format = AV_PIX_FMT_YUVA444P16;
            planar               = 4;
            break;
        case AVS_CS_YUVA422P16:
            st->codecpar->format = AV_PIX_FMT_YUVA422P16;
            planar               = 4;
            break;
        case AVS_CS_YUVA420P16:
            st->codecpar->format = AV_PIX_FMT_YUVA420P16;
            planar               = 4;
            break;
    /* Planar RGB pix_fmts (AviSynth+)  */
        case AVS_CS_RGBP:
            st->codecpar->format = AV_PIX_FMT_GBRP;
            planar               = 3;
            break;
        case AVS_CS_RGBP10:
            st->codecpar->format = AV_PIX_FMT_GBRP10;
            planar               = 3;
            break;
        case AVS_CS_RGBP12:
            st->codecpar->format = AV_PIX_FMT_GBRP12;
            planar               = 3;
            break;
        case AVS_CS_RGBP14:
            st->codecpar->format = AV_PIX_FMT_GBRP14;
            planar               = 3;
            break;
        case AVS_CS_RGBP16:
            st->codecpar->format = AV_PIX_FMT_GBRP16;
            planar               = 3;
            break;
    /* Planar RGB pix_fmts with Alpha (AviSynth+) */
        case AVS_CS_RGBAP:
            st->codecpar->format = AV_PIX_FMT_GBRAP;
            planar               = 5;
            break;
        case AVS_CS_RGBAP10:
            st->codecpar->format = AV_PIX_FMT_GBRAP10;
            planar               = 5;
            break;
        case AVS_CS_RGBAP12:
            st->codecpar->format = AV_PIX_FMT_GBRAP12;
            planar               = 5;
            break;
        case AVS_CS_RGBAP16:
            st->codecpar->format = AV_PIX_FMT_GBRAP16;
            planar               = 5;
            break;
    /* GRAY16 (AviSynth+) */
        case AVS_CS_Y16:
            st->codecpar->format = AV_PIX_FMT_GRAY16;
            planar               = 2;
            break;
    /* pix_fmts added in AviSynth 2.6 */
    
    d s's avatar
    d s committed
        case AVS_CS_YV24:
    
            st->codecpar->format = AV_PIX_FMT_YUV444P;
            planar               = 1;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_YV16:
    
            st->codecpar->format = AV_PIX_FMT_YUV422P;
            planar               = 1;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_YV411:
    
            st->codecpar->format = AV_PIX_FMT_YUV411P;
            planar               = 1;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_Y8:
    
            st->codecpar->format = AV_PIX_FMT_GRAY8;
            planar               = 2;
    
    d s's avatar
    d s committed
            break;
    
    /* 16-bit packed RGB pix_fmts (AviSynth+) */
        case AVS_CS_BGR48:
            st->codecpar->format = AV_PIX_FMT_BGR48;
            break;
        case AVS_CS_BGR64:
            st->codecpar->format = AV_PIX_FMT_BGRA64;
            break;
    
    d s's avatar
    d s committed
    #endif
    
    /* AviSynth 2.5 and AvxSynth pix_fmts */
    
    d s's avatar
    d s committed
        case AVS_CS_BGR24:
    
            st->codecpar->format = AV_PIX_FMT_BGR24;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_BGR32:
    
            st->codecpar->format = AV_PIX_FMT_RGB32;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_YUY2:
    
            st->codecpar->format = AV_PIX_FMT_YUYV422;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_YV12:
    
            st->codecpar->format = AV_PIX_FMT_YUV420P;
            planar               = 1;
    
    d s's avatar
    d s committed
            break;
        case AVS_CS_I420: // Is this even used anywhere?
    
            st->codecpar->format = AV_PIX_FMT_YUV420P;
            planar               = 1;
    
    d s's avatar
    d s committed
            break;
        default:
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            av_log(s, AV_LOG_ERROR,
                   "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
    
    d s's avatar
    d s committed
            avs->error = 1;
            return AVERROR_UNKNOWN;
        }
    
    d s's avatar
    d s committed
        switch (planar) {
    
    #ifdef USING_AVISYNTH
        case 5: // Planar RGB + Alpha
            avs->n_planes = 4;
            avs->planes   = avs_planes_rgba;
            break;
        case 4: // YUV + Alpha
            avs->n_planes = 4;
            avs->planes   = avs_planes_yuva;
            break;
        case 3: // Planar RGB
            avs->n_planes = 3;
            avs->planes   = avs_planes_rgb;
            break;
    #endif
    
    d s's avatar
    d s committed
        case 2: // Y8
            avs->n_planes = 1;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            avs->planes   = avs_planes_grey;
    
    d s's avatar
    d s committed
            break;
        case 1: // YUV
            avs->n_planes = 3;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            avs->planes   = avs_planes_yuv;
    
    d s's avatar
    d s committed
            break;
        default:
            avs->n_planes = 1;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            avs->planes   = avs_planes_packed;
    
    d s's avatar
    d s committed
        }
        return 0;
    }
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
    
    
        st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
        st->codecpar->sample_rate = avs->vi->audio_samples_per_second;
        st->codecpar->channels    = avs->vi->nchannels;
    
        st->duration              = avs->vi->num_audio_samples;
    
        avpriv_set_pts_info(st, 64, 1, avs->vi->audio_samples_per_second);
    
    d s's avatar
    d s committed
    
        switch (avs->vi->sample_type) {
        case AVS_SAMPLE_INT8:
    
            st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
    
    d s's avatar
    d s committed
            break;
        case AVS_SAMPLE_INT16:
    
            st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
    
    d s's avatar
    d s committed
            break;
        case AVS_SAMPLE_INT24:
    
            st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
    
    d s's avatar
    d s committed
            break;
        case AVS_SAMPLE_INT32:
    
            st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
    
    d s's avatar
    d s committed
            break;
        case AVS_SAMPLE_FLOAT:
    
            st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
    
    d s's avatar
    d s committed
            break;
        default:
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            av_log(s, AV_LOG_ERROR,
                   "unknown AviSynth sample type %d\n", avs->vi->sample_type);
    
    d s's avatar
    d s committed
            avs->error = 1;
            return AVERROR_UNKNOWN;
        }
        return 0;
    }
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_create_stream(AVFormatContext *s)
    {
    
    d s's avatar
    d s committed
        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;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_open_file(AVFormatContext *s)
    {
    
        AviSynthContext *avs = s->priv_data;
    
    d s's avatar
    d s committed
        AVS_Value arg, val;
        int ret;
    
    #ifdef USING_AVISYNTH
    
        char filename_ansi[MAX_PATH * 4];
        wchar_t filename_wc[MAX_PATH * 4];
    #endif
    
    d s's avatar
    d s committed
    
        if (ret = avisynth_context_create(s))
            return ret;
    
    #ifdef USING_AVISYNTH
    
        /* Convert UTF-8 to ANSI code page */
    
        MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
                            MAX_PATH * 4, NULL, NULL);
    
        arg = avs_new_value_string(filename_ansi);
    #else
    
    d s's avatar
    d s committed
        arg = avs_new_value_string(s->filename);
    
        val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
    
    d s's avatar
    d s committed
        if (avs_is_error(val)) {
            av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
            ret = AVERROR_UNKNOWN;
            goto fail;
    
    d s's avatar
    d s committed
        if (!avs_is_clip(val)) {
    
            av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
    
    d s's avatar
    d s committed
            ret = AVERROR_UNKNOWN;
            goto fail;
        }
    
    
        avs->clip = avs_library.avs_take_clip(val, avs->env);
        avs->vi   = avs_library.avs_get_video_info(avs->clip);
    
    d s's avatar
    d s committed
    
    
    #ifdef USING_AVISYNTH
    
        /* On Windows, FFmpeg supports AviSynth interface version 6 or higher.
         * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
         * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
         * as interface version 3 like 2.5.8, this needs to be special-cased. */
    
        if (avs_library.avs_get_version(avs->clip) < 6) {
    
            av_log(s, AV_LOG_ERROR,
    
                   "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
    
            ret = AVERROR_UNKNOWN;
            goto fail;
        }
    #endif
    
    
        /* Release the AVS_Value as it will go out of scope. */
    
        avs_library.avs_release_value(val);
    
    d s's avatar
    d s committed
    
        if (ret = avisynth_create_stream(s))
            goto fail;
    
        return 0;
    
    d s's avatar
    d s committed
    fail:
        avisynth_context_destroy(avs);
        return ret;
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
                                     AVPacket *pkt, int *discard)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
    
    d s's avatar
    d s committed
        avs->curr_stream %= s->nb_streams;
    
    
        *st = s->streams[avs->curr_stream];
    
    d s's avatar
    d s committed
        if ((*st)->discard == AVDISCARD_ALL)
            *discard = 1;
        else
            *discard = 0;
    
        return;
    }
    
    
    /* Copy AviSynth clip data into an AVPacket. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
                                          int discard)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
        AVS_VideoFrame *frame;
    
    d s's avatar
    d s committed
        unsigned char *dst_p;
        const unsigned char *src_p;
    
        int n, i, plane, rowsize, planeheight, pitch, bits;
    
    d s's avatar
    d s committed
        const char *error;
    
    d s's avatar
    d s committed
    
        if (avs->curr_frame >= avs->vi->num_frames)
            return AVERROR_EOF;
    
    
        /* This must happen even if the stream is discarded to prevent desync. */
    
        n = avs->curr_frame++;
    
    d s's avatar
    d s committed
        if (discard)
            return 0;
    
    
        /* Detect whether we're using AviSynth 2.6 or AviSynth+ by
         * looking for whether avs_is_planar_rgb exists. */
    
        int avsplus;
    
        if (GetProcAddress(avs_library.library, "avs_is_planar_rgb") == NULL)
            avsplus = 0;
        else
            avsplus = 1;
    
    
        /* avs_bits_per_pixel changed to AVSC_API with AviSynth 2.6, which
         * requires going through avs_library, while AvxSynth has it under
         * the older AVSC_INLINE type, so special-case this. */
    
        bits = avs_library.avs_bits_per_pixel(avs->vi);
    
    #else
        bits = avs_bits_per_pixel(avs->vi);
    
    d s's avatar
    d s committed
    
    
        /* Without the cast to int64_t, calculation overflows at about 9k x 9k
         * resolution. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        pkt->size = (((int64_t)avs->vi->width *
                      (int64_t)avs->vi->height) * bits) / 8;
    
    d s's avatar
    d s committed
        if (!pkt->size)
            return AVERROR_UNKNOWN;
    
        if (av_new_packet(pkt, pkt->size) < 0)
    
    d s's avatar
    d s committed
    
    
        pkt->pts      = n;
        pkt->dts      = n;
        pkt->duration = 1;
        pkt->stream_index = avs->curr_stream;
    
        frame = avs_library.avs_get_frame(avs->clip, n);
        error = avs_library.avs_clip_get_error(avs->clip);
    
    d s's avatar
    d s committed
        if (error) {
            av_log(s, AV_LOG_ERROR, "%s\n", error);
            avs->error = 1;
    
            av_packet_unref(pkt);
    
    d s's avatar
    d s committed
            return AVERROR_UNKNOWN;
        }
    
        dst_p = pkt->data;
        for (i = 0; i < avs->n_planes; i++) {
            plane = avs->planes[i];
    
    #ifdef USING_AVISYNTH
    
            src_p = avs_library.avs_get_read_ptr_p(frame, plane);
            pitch = avs_library.avs_get_pitch_p(frame, plane);
    
    
            rowsize     = avs_library.avs_get_row_size_p(frame, plane);
            planeheight = avs_library.avs_get_height_p(frame, plane);
    
    d s's avatar
    d s committed
            src_p = avs_get_read_ptr_p(frame, plane);
            pitch = avs_get_pitch_p(frame, plane);
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            rowsize     = avs_get_row_size_p(frame, plane);
    
    d s's avatar
    d s committed
            planeheight = avs_get_height_p(frame, plane);
    
    d s's avatar
    d s committed
    
    
    d s's avatar
    d s committed
            if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
                src_p = src_p + (planeheight - 1) * pitch;
                pitch = -pitch;
            }
    
    
    #ifdef USING_AVISYNTH
            /* Flip Planar RGB video. */
            if (avsplus && (avs_library.avs_is_planar_rgb(avs->vi) ||
                            avs_library.avs_is_planar_rgba(avs->vi)))
                pitch = -pitch;
    #endif
    
    
            avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
                                     rowsize, planeheight);
    
    d s's avatar
    d s committed
            dst_p += rowsize * planeheight;
        }
    
    
        avs_library.avs_release_video_frame(frame);
    
    d s's avatar
    d s committed
        return 0;
    }
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
                                          int discard)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
        AVRational fps, samplerate;
    
    d s's avatar
    d s committed
        const char *error;
    
    d s's avatar
    d s committed
    
        if (avs->curr_sample >= avs->vi->num_audio_samples)
            return AVERROR_EOF;
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        fps.num        = avs->vi->fps_numerator;
        fps.den        = avs->vi->fps_denominator;
    
    d s's avatar
    d s committed
        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)
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
                samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
                          avs->curr_sample;
    
    d s's avatar
    d s committed
            else
                samples = av_rescale_q(1, samplerate, fps);
        } else {
            samples = 1000;
        }
    
    
        /* After seeking, audio may catch up with video. */
    
    d s's avatar
    d s committed
        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;
    
    
        /* This must happen even if the stream is discarded to prevent desync. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        n                 = avs->curr_sample;
    
    d s's avatar
    d s committed
        avs->curr_sample += samples;
        if (discard)
            return 0;
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        pkt->size = avs_bytes_per_channel_sample(avs->vi) *
                    samples * avs->vi->nchannels;
    
    d s's avatar
    d s committed
        if (!pkt->size)
            return AVERROR_UNKNOWN;
    
        if (av_new_packet(pkt, pkt->size) < 0)
    
    d s's avatar
    d s committed
    
    
        pkt->pts      = n;
        pkt->dts      = n;
        pkt->duration = samples;
        pkt->stream_index = avs->curr_stream;
    
        avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
        error = avs_library.avs_clip_get_error(avs->clip);
    
    d s's avatar
    d s committed
        if (error) {
            av_log(s, AV_LOG_ERROR, "%s\n", error);
            avs->error = 1;
    
            av_packet_unref(pkt);
    
    d s's avatar
    d s committed
            return AVERROR_UNKNOWN;
        }
        return 0;
    }
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold int avisynth_read_header(AVFormatContext *s)
    {
    
    d s's avatar
    d s committed
        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;
    }
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
        AVStream *st;
        int discard = 0;
        int ret;
    
        if (avs->error)
            return AVERROR_UNKNOWN;
    
    
        /* If either stream reaches EOF, try to read the other one before
         * giving up. */
    
    d s's avatar
    d s committed
        avisynth_next_stream(s, &st, pkt, &discard);
    
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    
    d s's avatar
    d s committed
            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);
            }
        }
    
    d s's avatar
    d s committed
    }
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static av_cold int avisynth_read_close(AVFormatContext *s)
    {
    
    d s's avatar
    d s committed
        if (avpriv_lock_avformat())
            return AVERROR_UNKNOWN;
    
        avisynth_context_destroy(s->priv_data);
        avpriv_unlock_avformat();
        return 0;
    }
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
    static int avisynth_read_seek(AVFormatContext *s, int stream_index,
                                  int64_t timestamp, int flags)
    {
    
    d s's avatar
    d s committed
        AviSynthContext *avs = s->priv_data;
        AVStream *st;
        AVRational fps, samplerate;
    
        if (avs->error)
            return AVERROR_UNKNOWN;
    
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
        fps        = (AVRational) { avs->vi->fps_numerator,
                                    avs->vi->fps_denominator };
        samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
    
    d s's avatar
    d s committed
    
        st = s->streams[stream_index];
    
        if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
    
            /* AviSynth frame counts are signed int. */
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
            if ((timestamp >= avs->vi->num_frames) ||
                (timestamp > INT_MAX)              ||
                (timestamp < 0))
    
    d s's avatar
    d s committed
                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;
    
            /* Force frame granularity for seeking. */
    
    d s's avatar
    d s committed
            if (avs_has_video(avs->vi)) {
    
    Stephen Hutchinson's avatar
    Stephen Hutchinson committed
                avs->curr_frame  = av_rescale_q(timestamp, fps, samplerate);
    
    d s's avatar
    d s committed
                avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
            } else {
                avs->curr_sample = timestamp;
            }
    
    d s's avatar
    d s committed
        return 0;
    
    d s's avatar
    d s committed
        .long_name      = NULL_IF_CONFIG_SMALL("AviSynth script"),
        .priv_data_size = sizeof(AviSynthContext),
    
        .read_header    = avisynth_read_header,
        .read_packet    = avisynth_read_packet,
        .read_close     = avisynth_read_close,
        .read_seek      = avisynth_read_seek,
        .extensions     = "avs",