2 * AviSynth/AvxSynth support
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
21 #include "libavutil/internal.h"
22 #include "libavcodec/internal.h"
27 /* Enable function pointer definitions for runtime loading. */
28 #define AVSC_NO_DECLSPEC
30 /* Platform-specific directives for AviSynth vs AvxSynth. */
34 #include "compat/avisynth/avisynth_c.h"
35 #define AVISYNTH_LIB "avisynth"
36 #define USING_AVISYNTH
39 #include "compat/avisynth/avxsynth_c.h"
40 #define AVISYNTH_NAME "libavxsynth"
41 #define AVISYNTH_LIB AVISYNTH_NAME SLIBSUF
43 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_LOCAL)
44 #define GetProcAddress dlsym
45 #define FreeLibrary dlclose
48 typedef struct AviSynthLibrary {
50 #define AVSC_DECLARE_FUNC(name) name ## _func name
51 AVSC_DECLARE_FUNC(avs_bit_blt);
52 AVSC_DECLARE_FUNC(avs_clip_get_error);
53 AVSC_DECLARE_FUNC(avs_create_script_environment);
54 AVSC_DECLARE_FUNC(avs_delete_script_environment);
55 AVSC_DECLARE_FUNC(avs_get_audio);
56 AVSC_DECLARE_FUNC(avs_get_error);
57 AVSC_DECLARE_FUNC(avs_get_frame);
58 AVSC_DECLARE_FUNC(avs_get_version);
59 AVSC_DECLARE_FUNC(avs_get_video_info);
60 AVSC_DECLARE_FUNC(avs_invoke);
61 AVSC_DECLARE_FUNC(avs_release_clip);
62 AVSC_DECLARE_FUNC(avs_release_value);
63 AVSC_DECLARE_FUNC(avs_release_video_frame);
64 AVSC_DECLARE_FUNC(avs_take_clip);
66 AVSC_DECLARE_FUNC(avs_bits_per_pixel);
67 AVSC_DECLARE_FUNC(avs_get_height_p);
68 AVSC_DECLARE_FUNC(avs_get_pitch_p);
69 AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
70 AVSC_DECLARE_FUNC(avs_get_row_size_p);
71 AVSC_DECLARE_FUNC(avs_is_yv24);
72 AVSC_DECLARE_FUNC(avs_is_yv16);
73 AVSC_DECLARE_FUNC(avs_is_yv411);
74 AVSC_DECLARE_FUNC(avs_is_y8);
76 #undef AVSC_DECLARE_FUNC
79 typedef struct AviSynthContext {
80 AVS_ScriptEnvironment *env;
82 const AVS_VideoInfo *vi;
84 /* avisynth_read_packet_video() iterates over this. */
94 /* Linked list pointers. */
95 struct AviSynthContext *next;
98 static const int avs_planes_packed[1] = { 0 };
99 static const int avs_planes_grey[1] = { AVS_PLANAR_Y };
100 static const int avs_planes_yuv[3] = { AVS_PLANAR_Y, AVS_PLANAR_U,
103 /* A conflict between C++ global objects, atexit, and dynamic loading requires
104 * us to register our own atexit handler to prevent double freeing. */
105 static AviSynthLibrary avs_library;
106 static int avs_atexit_called = 0;
108 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
109 static AviSynthContext *avs_ctx_list = NULL;
111 static av_cold void avisynth_atexit_handler(void);
113 static av_cold int avisynth_load_library(void)
115 avs_library.library = LoadLibrary(AVISYNTH_LIB);
116 if (!avs_library.library)
117 return AVERROR_UNKNOWN;
119 #define LOAD_AVS_FUNC(name, continue_on_fail) \
121 (void *)GetProcAddress(avs_library.library, #name); \
122 if (!continue_on_fail && !avs_library.name) \
125 LOAD_AVS_FUNC(avs_bit_blt, 0);
126 LOAD_AVS_FUNC(avs_clip_get_error, 0);
127 LOAD_AVS_FUNC(avs_create_script_environment, 0);
128 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
129 LOAD_AVS_FUNC(avs_get_audio, 0);
130 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
131 LOAD_AVS_FUNC(avs_get_frame, 0);
132 LOAD_AVS_FUNC(avs_get_version, 0);
133 LOAD_AVS_FUNC(avs_get_video_info, 0);
134 LOAD_AVS_FUNC(avs_invoke, 0);
135 LOAD_AVS_FUNC(avs_release_clip, 0);
136 LOAD_AVS_FUNC(avs_release_value, 0);
137 LOAD_AVS_FUNC(avs_release_video_frame, 0);
138 LOAD_AVS_FUNC(avs_take_clip, 0);
139 #ifdef USING_AVISYNTH
140 LOAD_AVS_FUNC(avs_bits_per_pixel, 1);
141 LOAD_AVS_FUNC(avs_get_height_p, 1);
142 LOAD_AVS_FUNC(avs_get_pitch_p, 1);
143 LOAD_AVS_FUNC(avs_get_read_ptr_p, 1);
144 LOAD_AVS_FUNC(avs_get_row_size_p, 1);
145 LOAD_AVS_FUNC(avs_is_yv24, 1);
146 LOAD_AVS_FUNC(avs_is_yv16, 1);
147 LOAD_AVS_FUNC(avs_is_yv411, 1);
148 LOAD_AVS_FUNC(avs_is_y8, 1);
152 atexit(avisynth_atexit_handler);
156 FreeLibrary(avs_library.library);
157 return AVERROR_UNKNOWN;
160 /* Note that avisynth_context_create and avisynth_context_destroy
161 * do not allocate or free the actual context! That is taken care of
163 static av_cold int avisynth_context_create(AVFormatContext *s)
165 AviSynthContext *avs = s->priv_data;
168 if (!avs_library.library)
169 if (ret = avisynth_load_library())
172 avs->env = avs_library.avs_create_script_environment(3);
173 if (avs_library.avs_get_error) {
174 const char *error = avs_library.avs_get_error(avs->env);
176 av_log(s, AV_LOG_ERROR, "%s\n", error);
177 return AVERROR_UNKNOWN;
184 avs->next = avs_ctx_list;
191 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
193 if (avs_atexit_called)
196 if (avs == avs_ctx_list) {
197 avs_ctx_list = avs->next;
199 AviSynthContext *prev = avs_ctx_list;
200 while (prev->next != avs)
202 prev->next = avs->next;
206 avs_library.avs_release_clip(avs->clip);
210 avs_library.avs_delete_script_environment(avs->env);
215 static av_cold void avisynth_atexit_handler(void)
217 AviSynthContext *avs = avs_ctx_list;
220 AviSynthContext *next = avs->next;
221 avisynth_context_destroy(avs);
224 FreeLibrary(avs_library.library);
226 avs_atexit_called = 1;
229 /* Create AVStream from audio and video data. */
230 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
232 AviSynthContext *avs = s->priv_data;
233 int planar = 0; // 0: packed, 1: YUV, 2: Y8
235 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
236 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
237 st->codecpar->width = avs->vi->width;
238 st->codecpar->height = avs->vi->height;
240 st->avg_frame_rate = (AVRational) { avs->vi->fps_numerator,
241 avs->vi->fps_denominator };
243 st->duration = avs->vi->num_frames;
244 st->nb_frames = avs->vi->num_frames;
245 avpriv_set_pts_info(st, 32, avs->vi->fps_denominator, avs->vi->fps_numerator);
247 switch (avs->vi->pixel_type) {
248 #ifdef USING_AVISYNTH
250 st->codecpar->format = AV_PIX_FMT_YUV444P;
254 st->codecpar->format = AV_PIX_FMT_YUV422P;
258 st->codecpar->format = AV_PIX_FMT_YUV411P;
262 st->codecpar->format = AV_PIX_FMT_GRAY8;
267 st->codecpar->format = AV_PIX_FMT_BGR24;
270 st->codecpar->format = AV_PIX_FMT_RGB32;
273 st->codecpar->format = AV_PIX_FMT_YUYV422;
276 st->codecpar->format = AV_PIX_FMT_YUV420P;
279 case AVS_CS_I420: // Is this even used anywhere?
280 st->codecpar->format = AV_PIX_FMT_YUV420P;
284 av_log(s, AV_LOG_ERROR,
285 "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
287 return AVERROR_UNKNOWN;
293 avs->planes = avs_planes_grey;
297 avs->planes = avs_planes_yuv;
301 avs->planes = avs_planes_packed;
306 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
308 AviSynthContext *avs = s->priv_data;
310 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
311 st->codecpar->sample_rate = avs->vi->audio_samples_per_second;
312 st->codecpar->channels = avs->vi->nchannels;
313 st->duration = avs->vi->num_audio_samples;
314 avpriv_set_pts_info(st, 64, 1, avs->vi->audio_samples_per_second);
316 switch (avs->vi->sample_type) {
317 case AVS_SAMPLE_INT8:
318 st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
320 case AVS_SAMPLE_INT16:
321 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
323 case AVS_SAMPLE_INT24:
324 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
326 case AVS_SAMPLE_INT32:
327 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
329 case AVS_SAMPLE_FLOAT:
330 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
333 av_log(s, AV_LOG_ERROR,
334 "unknown AviSynth sample type %d\n", avs->vi->sample_type);
336 return AVERROR_UNKNOWN;
341 static int avisynth_create_stream(AVFormatContext *s)
343 AviSynthContext *avs = s->priv_data;
348 if (avs_has_video(avs->vi)) {
349 st = avformat_new_stream(s, NULL);
351 return AVERROR_UNKNOWN;
353 if (ret = avisynth_create_stream_video(s, st))
356 if (avs_has_audio(avs->vi)) {
357 st = avformat_new_stream(s, NULL);
359 return AVERROR_UNKNOWN;
361 if (ret = avisynth_create_stream_audio(s, st))
367 static int avisynth_open_file(AVFormatContext *s)
369 AviSynthContext *avs = s->priv_data;
372 #ifdef USING_AVISYNTH
373 char filename_ansi[MAX_PATH * 4];
374 wchar_t filename_wc[MAX_PATH * 4];
377 if (ret = avisynth_context_create(s))
380 #ifdef USING_AVISYNTH
381 /* Convert UTF-8 to ANSI code page */
382 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
383 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
384 MAX_PATH * 4, NULL, NULL);
385 arg = avs_new_value_string(filename_ansi);
387 arg = avs_new_value_string(s->filename);
389 val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
390 if (avs_is_error(val)) {
391 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
392 ret = AVERROR_UNKNOWN;
395 if (!avs_is_clip(val)) {
396 av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
397 ret = AVERROR_UNKNOWN;
401 avs->clip = avs_library.avs_take_clip(val, avs->env);
402 avs->vi = avs_library.avs_get_video_info(avs->clip);
404 #ifdef USING_AVISYNTH
405 /* On Windows, FFmpeg supports AviSynth interface version 6 or higher.
406 * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
407 * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
408 * as interface version 3 like 2.5.8, this needs to be special-cased. */
410 if (avs_library.avs_get_version(avs->clip) < 6) {
411 av_log(s, AV_LOG_ERROR,
412 "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
413 ret = AVERROR_UNKNOWN;
418 /* Release the AVS_Value as it will go out of scope. */
419 avs_library.avs_release_value(val);
421 if (ret = avisynth_create_stream(s))
427 avisynth_context_destroy(avs);
431 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
432 AVPacket *pkt, int *discard)
434 AviSynthContext *avs = s->priv_data;
437 avs->curr_stream %= s->nb_streams;
439 *st = s->streams[avs->curr_stream];
440 if ((*st)->discard == AVDISCARD_ALL)
448 /* Copy AviSynth clip data into an AVPacket. */
449 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
452 AviSynthContext *avs = s->priv_data;
453 AVS_VideoFrame *frame;
454 unsigned char *dst_p;
455 const unsigned char *src_p;
456 int n, i, plane, rowsize, planeheight, pitch, bits;
459 if (avs->curr_frame >= avs->vi->num_frames)
462 /* This must happen even if the stream is discarded to prevent desync. */
463 n = avs->curr_frame++;
467 #ifdef USING_AVISYNTH
468 /* Define the bpp values for the new AviSynth 2.6 colorspaces.
469 * Since AvxSynth doesn't have these functions, special-case
470 * it in order to avoid implicit declaration errors. */
472 if (avs_library.avs_is_yv24(avs->vi))
474 else if (avs_library.avs_is_yv16(avs->vi))
476 else if (avs_library.avs_is_yv411(avs->vi))
478 else if (avs_library.avs_is_y8(avs->vi))
481 bits = avs_library.avs_bits_per_pixel(avs->vi);
483 bits = avs_bits_per_pixel(avs->vi);
486 /* Without the cast to int64_t, calculation overflows at about 9k x 9k
488 pkt->size = (((int64_t)avs->vi->width *
489 (int64_t)avs->vi->height) * bits) / 8;
491 return AVERROR_UNKNOWN;
493 if (av_new_packet(pkt, pkt->size) < 0)
494 return AVERROR(ENOMEM);
499 pkt->stream_index = avs->curr_stream;
501 frame = avs_library.avs_get_frame(avs->clip, n);
502 error = avs_library.avs_clip_get_error(avs->clip);
504 av_log(s, AV_LOG_ERROR, "%s\n", error);
506 av_packet_unref(pkt);
507 return AVERROR_UNKNOWN;
511 for (i = 0; i < avs->n_planes; i++) {
512 plane = avs->planes[i];
513 #ifdef USING_AVISYNTH
514 src_p = avs_library.avs_get_read_ptr_p(frame, plane);
515 pitch = avs_library.avs_get_pitch_p(frame, plane);
517 rowsize = avs_library.avs_get_row_size_p(frame, plane);
518 planeheight = avs_library.avs_get_height_p(frame, plane);
520 src_p = avs_get_read_ptr_p(frame, plane);
521 pitch = avs_get_pitch_p(frame, plane);
523 rowsize = avs_get_row_size_p(frame, plane);
524 planeheight = avs_get_height_p(frame, plane);
527 /* Flip RGB video. */
528 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
529 src_p = src_p + (planeheight - 1) * pitch;
533 avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
534 rowsize, planeheight);
535 dst_p += rowsize * planeheight;
538 avs_library.avs_release_video_frame(frame);
542 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
545 AviSynthContext *avs = s->priv_data;
546 AVRational fps, samplerate;
551 if (avs->curr_sample >= avs->vi->num_audio_samples)
554 fps.num = avs->vi->fps_numerator;
555 fps.den = avs->vi->fps_denominator;
556 samplerate.num = avs->vi->audio_samples_per_second;
559 if (avs_has_video(avs->vi)) {
560 if (avs->curr_frame < avs->vi->num_frames)
561 samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
564 samples = av_rescale_q(1, samplerate, fps);
569 /* After seeking, audio may catch up with video. */
576 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
577 samples = avs->vi->num_audio_samples - avs->curr_sample;
579 /* This must happen even if the stream is discarded to prevent desync. */
580 n = avs->curr_sample;
581 avs->curr_sample += samples;
585 pkt->size = avs_bytes_per_channel_sample(avs->vi) *
586 samples * avs->vi->nchannels;
588 return AVERROR_UNKNOWN;
590 if (av_new_packet(pkt, pkt->size) < 0)
591 return AVERROR(ENOMEM);
595 pkt->duration = samples;
596 pkt->stream_index = avs->curr_stream;
598 avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
599 error = avs_library.avs_clip_get_error(avs->clip);
601 av_log(s, AV_LOG_ERROR, "%s\n", error);
603 av_packet_unref(pkt);
604 return AVERROR_UNKNOWN;
609 static av_cold int avisynth_read_header(AVFormatContext *s)
613 // Calling library must implement a lock for thread-safe opens.
614 if (ret = avpriv_lock_avformat())
617 if (ret = avisynth_open_file(s)) {
618 avpriv_unlock_avformat();
622 avpriv_unlock_avformat();
626 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
628 AviSynthContext *avs = s->priv_data;
634 return AVERROR_UNKNOWN;
636 /* If either stream reaches EOF, try to read the other one before
638 avisynth_next_stream(s, &st, pkt, &discard);
639 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
640 ret = avisynth_read_packet_video(s, pkt, discard);
641 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
642 avisynth_next_stream(s, &st, pkt, &discard);
643 return avisynth_read_packet_audio(s, pkt, discard);
646 ret = avisynth_read_packet_audio(s, pkt, discard);
647 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
648 avisynth_next_stream(s, &st, pkt, &discard);
649 return avisynth_read_packet_video(s, pkt, discard);
656 static av_cold int avisynth_read_close(AVFormatContext *s)
658 if (avpriv_lock_avformat())
659 return AVERROR_UNKNOWN;
661 avisynth_context_destroy(s->priv_data);
662 avpriv_unlock_avformat();
666 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
667 int64_t timestamp, int flags)
669 AviSynthContext *avs = s->priv_data;
671 AVRational fps, samplerate;
674 return AVERROR_UNKNOWN;
676 fps = (AVRational) { avs->vi->fps_numerator,
677 avs->vi->fps_denominator };
678 samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
680 st = s->streams[stream_index];
681 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
682 /* AviSynth frame counts are signed int. */
683 if ((timestamp >= avs->vi->num_frames) ||
684 (timestamp > INT_MAX) ||
687 avs->curr_frame = timestamp;
688 if (avs_has_audio(avs->vi))
689 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
691 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
693 /* Force frame granularity for seeking. */
694 if (avs_has_video(avs->vi)) {
695 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
696 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
698 avs->curr_sample = timestamp;
705 AVInputFormat ff_avisynth_demuxer = {
707 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
708 .priv_data_size = sizeof(AviSynthContext),
709 .read_header = avisynth_read_header,
710 .read_packet = avisynth_read_packet,
711 .read_close = avisynth_read_close,
712 .read_seek = avisynth_read_seek,