3 * Copyright (c) 2012 AvxSynth Team.
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.
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.
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
23 #include "libavcodec/internal.h"
25 // Enable function pointer definitions for runtime loading.
26 #define AVSC_NO_DECLSPEC
28 // Shut up ffmpeg error messages.
29 // avisynth_c.h contains inline functions that call these functions.
34 // Platform-specific directives for AviSynth vs AvxSynth.
38 #include "compat/avisynth/avisynth_c.h"
39 #define AVISYNTH_LIB "avisynth"
42 #include "compat/avisynth/avxsynth_c.h"
43 #if defined (__APPLE__)
44 #define AVISYNTH_LIB "libavxsynth.dylib"
46 #define AVISYNTH_LIB "libavxsynth.so"
49 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
50 #define GetProcAddress dlsym
51 #define FreeLibrary dlclose
54 // AvxSynth doesn't have these colorspaces, so disable them
56 #define avs_is_yv24(vi) 0
57 #define avs_is_yv16(vi) 0
58 #define avs_is_yv411(vi) 0
59 #define avs_is_y8(vi) 0
64 #define AVSC_DECLARE_FUNC(name) name##_func name
65 AVSC_DECLARE_FUNC(avs_create_script_environment);
66 AVSC_DECLARE_FUNC(avs_delete_script_environment);
67 AVSC_DECLARE_FUNC(avs_get_error);
68 AVSC_DECLARE_FUNC(avs_clip_get_error);
69 AVSC_DECLARE_FUNC(avs_invoke);
70 AVSC_DECLARE_FUNC(avs_release_value);
71 AVSC_DECLARE_FUNC(avs_get_video_info);
72 AVSC_DECLARE_FUNC(avs_take_clip);
73 AVSC_DECLARE_FUNC(avs_release_clip);
74 AVSC_DECLARE_FUNC(avs_bit_blt);
75 AVSC_DECLARE_FUNC(avs_get_audio);
76 AVSC_DECLARE_FUNC(avs_get_frame);
77 AVSC_DECLARE_FUNC(avs_release_video_frame);
78 #undef AVSC_DECLARE_FUNC
81 struct AviSynthContext {
82 AVS_ScriptEnvironment *env;
84 const AVS_VideoInfo *vi;
86 // avisynth_read_packet_video() iterates over this.
96 // Linked list pointers.
97 struct AviSynthContext *next;
99 typedef struct AviSynthContext AviSynthContext;
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, AVS_PLANAR_V};
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 = NULL;
108 static int avs_atexit_called = 0;
110 // Linked list of AviSynthContexts. An atexit handler destroys this list.
111 static AviSynthContext *avs_ctx_list = NULL;
113 static av_cold void avisynth_atexit_handler(void);
115 static av_cold int avisynth_load_library(void) {
116 avs_library = av_mallocz(sizeof(AviSynthLibrary));
118 return AVERROR_UNKNOWN;
120 avs_library->library = LoadLibrary(AVISYNTH_LIB);
121 if (!avs_library->library)
124 #define LOAD_AVS_FUNC(name, continue_on_fail) \
126 avs_library->name = (void*)GetProcAddress(avs_library->library, #name); \
127 if(!continue_on_fail && !avs_library->name) \
130 LOAD_AVS_FUNC(avs_create_script_environment, 0);
131 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
132 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
133 LOAD_AVS_FUNC(avs_clip_get_error, 0);
134 LOAD_AVS_FUNC(avs_invoke, 0);
135 LOAD_AVS_FUNC(avs_release_value, 0);
136 LOAD_AVS_FUNC(avs_get_video_info, 0);
137 LOAD_AVS_FUNC(avs_take_clip, 0);
138 LOAD_AVS_FUNC(avs_release_clip, 0);
139 LOAD_AVS_FUNC(avs_bit_blt, 0);
140 LOAD_AVS_FUNC(avs_get_audio, 0);
141 LOAD_AVS_FUNC(avs_get_frame, 0);
142 LOAD_AVS_FUNC(avs_release_video_frame, 0);
145 atexit(avisynth_atexit_handler);
149 FreeLibrary(avs_library->library);
151 av_freep(&avs_library);
152 return AVERROR_UNKNOWN;
155 // Note that avisynth_context_create and avisynth_context_destroy
156 // do not allocate or free the actual context! That is taken care of
158 static av_cold int avisynth_context_create(AVFormatContext *s) {
159 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
163 if (ret = avisynth_load_library())
167 avs->env = avs_library->avs_create_script_environment(3);
168 if (avs_library->avs_get_error) {
169 const char *error = avs_library->avs_get_error(avs->env);
171 av_log(s, AV_LOG_ERROR, "%s\n", error);
172 return AVERROR_UNKNOWN;
179 avs->next = avs_ctx_list;
186 static av_cold void avisynth_context_destroy(AviSynthContext *avs) {
187 if (avs_atexit_called)
190 if (avs == avs_ctx_list) {
191 avs_ctx_list = avs->next;
193 AviSynthContext *prev = avs_ctx_list;
194 while (prev->next != avs)
196 prev->next = avs->next;
200 avs_library->avs_release_clip(avs->clip);
204 avs_library->avs_delete_script_environment(avs->env);
209 static av_cold void avisynth_atexit_handler(void) {
210 AviSynthContext *avs = avs_ctx_list;
213 AviSynthContext *next = avs->next;
214 avisynth_context_destroy(avs);
217 FreeLibrary(avs_library->library);
218 av_freep(&avs_library);
220 avs_atexit_called = 1;
223 // Create AVStream from audio and video data.
224 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st) {
225 AviSynthContext *avs = s->priv_data;
226 int planar = 0; // 0: packed, 1: YUV, 2: Y8
228 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
229 st->codec->codec_id = CODEC_ID_RAWVIDEO;
230 st->codec->width = avs->vi->width;
231 st->codec->height = avs->vi->height;
233 st->time_base = (AVRational) {avs->vi->fps_denominator, avs->vi->fps_numerator};
234 st->avg_frame_rate = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
236 st->duration = avs->vi->num_frames;
237 st->nb_frames = avs->vi->num_frames;
239 switch (avs->vi->pixel_type) {
242 st->codec->pix_fmt = AV_PIX_FMT_YUV444P;
246 st->codec->pix_fmt = AV_PIX_FMT_YUV422P;
250 st->codec->pix_fmt = AV_PIX_FMT_YUV411P;
254 st->codec->pix_fmt = AV_PIX_FMT_GRAY8;
259 st->codec->pix_fmt = AV_PIX_FMT_BGR24;
262 st->codec->pix_fmt = AV_PIX_FMT_RGB32;
265 st->codec->pix_fmt = AV_PIX_FMT_YUYV422;
268 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
271 case AVS_CS_I420: // Is this even used anywhere?
272 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
276 av_log(s, AV_LOG_ERROR, "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
278 return AVERROR_UNKNOWN;
284 avs->planes = avs_planes_grey;
288 avs->planes = avs_planes_yuv;
292 avs->planes = avs_planes_packed;
297 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st) {
298 AviSynthContext *avs = s->priv_data;
300 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
301 st->codec->sample_rate = avs->vi->audio_samples_per_second;
302 st->codec->channels = avs->vi->nchannels;
303 st->time_base = (AVRational) {1, avs->vi->audio_samples_per_second};
305 switch (avs->vi->sample_type) {
306 case AVS_SAMPLE_INT8:
307 st->codec->codec_id = CODEC_ID_PCM_U8;
309 case AVS_SAMPLE_INT16:
310 st->codec->codec_id = CODEC_ID_PCM_S16LE;
312 case AVS_SAMPLE_INT24:
313 st->codec->codec_id = CODEC_ID_PCM_S24LE;
315 case AVS_SAMPLE_INT32:
316 st->codec->codec_id = CODEC_ID_PCM_S32LE;
318 case AVS_SAMPLE_FLOAT:
319 st->codec->codec_id = CODEC_ID_PCM_F32LE;
322 av_log(s, AV_LOG_ERROR, "unknown AviSynth sample type %d\n", avs->vi->sample_type);
324 return AVERROR_UNKNOWN;
329 static int avisynth_create_stream(AVFormatContext *s) {
330 AviSynthContext *avs = s->priv_data;
335 if (avs_has_video(avs->vi)) {
336 st = avformat_new_stream(s, NULL);
338 return AVERROR_UNKNOWN;
340 if (ret = avisynth_create_stream_video(s, st))
343 if (avs_has_audio(avs->vi)) {
344 st = avformat_new_stream(s, NULL);
346 return AVERROR_UNKNOWN;
348 if (ret = avisynth_create_stream_audio(s, st))
354 static int avisynth_open_file(AVFormatContext *s) {
355 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
359 char filename_ansi[MAX_PATH * 4];
360 wchar_t filename_wc[MAX_PATH * 4];
363 if (ret = avisynth_context_create(s))
367 // Convert UTF-8 to ANSI code page
368 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
369 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi, MAX_PATH * 4, NULL, NULL);
370 arg = avs_new_value_string(filename_ansi);
372 arg = avs_new_value_string(s->filename);
374 val = avs_library->avs_invoke(avs->env, "Import", arg, 0);
375 if (avs_is_error(val)) {
376 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
377 ret = AVERROR_UNKNOWN;
380 if (!avs_is_clip(val)) {
381 av_log(s, AV_LOG_ERROR, "%s\n", "AviSynth script did not return a clip");
382 ret = AVERROR_UNKNOWN;
386 avs->clip = avs_library->avs_take_clip(val, avs->env);
387 avs->vi = avs_library->avs_get_video_info(avs->clip);
389 // Release the AVS_Value as it will go out of scope.
390 avs_library->avs_release_value(val);
392 if (ret = avisynth_create_stream(s))
398 avisynth_context_destroy(avs);
402 static void avisynth_next_stream(AVFormatContext *s, AVStream **st, AVPacket *pkt, int *discard) {
403 AviSynthContext *avs = s->priv_data;
405 pkt->stream_index = avs->curr_stream++;
406 avs->curr_stream %= s->nb_streams;
408 *st = s->streams[pkt->stream_index];
409 if ((*st)->discard == AVDISCARD_ALL)
417 // Copy AviSynth clip data into an AVPacket.
418 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt, int discard) {
419 AviSynthContext *avs = s->priv_data;
420 AVS_VideoFrame *frame;
421 unsigned char *dst_p;
422 const unsigned char *src_p;
423 int n, i, plane, rowsize, planeheight, pitch, bits;
426 if (avs->curr_frame >= avs->vi->num_frames)
429 // This must happen even if the stream is discarded to prevent desync.
430 n = avs->curr_frame++;
438 // Define the bpp values for the new AviSynth 2.6 colorspaces
439 if (avs_is_yv24(avs->vi)) {
441 } else if (avs_is_yv16(avs->vi)) {
443 } else if (avs_is_yv411(avs->vi)) {
445 } else if (avs_is_y8(avs->vi)) {
448 bits = avs_bits_per_pixel(avs->vi);
451 // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.
452 pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;
454 return AVERROR_UNKNOWN;
455 pkt->data = av_malloc(pkt->size);
457 return AVERROR_UNKNOWN;
459 frame = avs_library->avs_get_frame(avs->clip, n);
460 error = avs_library->avs_clip_get_error(avs->clip);
462 av_log(s, AV_LOG_ERROR, "%s\n", error);
464 av_freep(&pkt->data);
465 return AVERROR_UNKNOWN;
469 for (i = 0; i < avs->n_planes; i++) {
470 plane = avs->planes[i];
471 src_p = avs_get_read_ptr_p(frame, plane);
472 rowsize = avs_get_row_size_p(frame, plane);
473 planeheight = avs_get_height_p(frame, plane);
474 pitch = avs_get_pitch_p(frame, plane);
477 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
478 src_p = src_p + (planeheight - 1) * pitch;
482 avs_library->avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch, rowsize, planeheight);
483 dst_p += rowsize * planeheight;
486 avs_library->avs_release_video_frame(frame);
490 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt, int discard) {
491 AviSynthContext *avs = s->priv_data;
492 AVRational fps, samplerate;
497 if (avs->curr_sample >= avs->vi->num_audio_samples)
500 fps.num = avs->vi->fps_numerator;
501 fps.den = avs->vi->fps_denominator;
502 samplerate.num = avs->vi->audio_samples_per_second;
505 if (avs_has_video(avs->vi)) {
506 if (avs->curr_frame < avs->vi->num_frames)
507 samples = av_rescale_q(avs->curr_frame, samplerate, fps) - avs->curr_sample;
509 samples = av_rescale_q(1, samplerate, fps);
514 // After seeking, audio may catch up with video.
521 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
522 samples = avs->vi->num_audio_samples - avs->curr_sample;
524 // This must happen even if the stream is discarded to prevent desync.
525 n = avs->curr_sample;
526 avs->curr_sample += samples;
532 pkt->duration = samples;
534 pkt->size = avs_bytes_per_channel_sample(avs->vi) * samples * avs->vi->nchannels;
536 return AVERROR_UNKNOWN;
537 pkt->data = av_malloc(pkt->size);
539 return AVERROR_UNKNOWN;
541 avs_library->avs_get_audio(avs->clip, pkt->data, n, samples);
542 error = avs_library->avs_clip_get_error(avs->clip);
544 av_log(s, AV_LOG_ERROR, "%s\n", error);
546 av_freep(&pkt->data);
547 return AVERROR_UNKNOWN;
552 static av_cold int avisynth_read_header(AVFormatContext *s) {
555 // Calling library must implement a lock for thread-safe opens.
556 if (ret = avpriv_lock_avformat())
559 if (ret = avisynth_open_file(s)) {
560 avpriv_unlock_avformat();
564 avpriv_unlock_avformat();
568 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt) {
569 AviSynthContext *avs = s->priv_data;
575 return AVERROR_UNKNOWN;
577 pkt->destruct = av_destruct_packet;
579 // If either stream reaches EOF, try to read the other one before giving up.
580 avisynth_next_stream(s, &st, pkt, &discard);
581 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
582 ret = avisynth_read_packet_video(s, pkt, discard);
583 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
584 avisynth_next_stream(s, &st, pkt, &discard);
585 return avisynth_read_packet_audio(s, pkt, discard);
589 ret = avisynth_read_packet_audio(s, pkt, discard);
590 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
591 avisynth_next_stream(s, &st, pkt, &discard);
592 return avisynth_read_packet_video(s, pkt, discard);
598 static av_cold int avisynth_read_close(AVFormatContext *s) {
599 if (avpriv_lock_avformat())
600 return AVERROR_UNKNOWN;
602 avisynth_context_destroy(s->priv_data);
603 avpriv_unlock_avformat();
607 static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
608 AviSynthContext *avs = s->priv_data;
610 AVRational fps, samplerate;
613 return AVERROR_UNKNOWN;
615 fps = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
616 samplerate = (AVRational) {avs->vi->audio_samples_per_second, 1};
618 st = s->streams[stream_index];
619 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
620 // AviSynth frame counts are signed int.
621 if ((timestamp >= avs->vi->num_frames) || (timestamp > INT_MAX) || (timestamp < 0))
623 avs->curr_frame = timestamp;
624 if (avs_has_audio(avs->vi))
625 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
627 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
629 // Force frame granularity for seeking.
630 if (avs_has_video(avs->vi)) {
631 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
632 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
634 avs->curr_sample = timestamp;
641 AVInputFormat ff_avisynth_demuxer = {
643 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
644 .priv_data_size = sizeof(AviSynthContext),
645 .read_header = avisynth_read_header,
646 .read_packet = avisynth_read_packet,
647 .read_close = avisynth_read_close,
648 .read_seek = avisynth_read_seek,