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"
26 /* Enable function pointer definitions for runtime loading. */
27 #define AVSC_NO_DECLSPEC
29 /* Platform-specific directives for AviSynth vs AvxSynth. */
33 #include "compat/avisynth/avisynth_c.h"
34 #include "compat/avisynth/avisynth_c_25.h"
35 #define AVISYNTH_LIB "avisynth"
36 #define USING_AVISYNTH
39 #include "compat/avisynth/avxsynth_c.h"
40 #if defined (__APPLE__)
41 #define AVISYNTH_LIB "libavxsynth.dylib"
43 #define AVISYNTH_LIB "libavxsynth.so"
46 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_LOCAL)
47 #define GetProcAddress dlsym
48 #define FreeLibrary dlclose
51 typedef struct AviSynthLibrary {
53 #define AVSC_DECLARE_FUNC(name) name ## _func name
54 AVSC_DECLARE_FUNC(avs_bit_blt);
55 AVSC_DECLARE_FUNC(avs_clip_get_error);
56 AVSC_DECLARE_FUNC(avs_create_script_environment);
57 AVSC_DECLARE_FUNC(avs_delete_script_environment);
58 AVSC_DECLARE_FUNC(avs_get_audio);
59 AVSC_DECLARE_FUNC(avs_get_error);
60 AVSC_DECLARE_FUNC(avs_get_frame);
61 AVSC_DECLARE_FUNC(avs_get_version);
62 AVSC_DECLARE_FUNC(avs_get_video_info);
63 AVSC_DECLARE_FUNC(avs_invoke);
64 AVSC_DECLARE_FUNC(avs_release_clip);
65 AVSC_DECLARE_FUNC(avs_release_value);
66 AVSC_DECLARE_FUNC(avs_release_video_frame);
67 AVSC_DECLARE_FUNC(avs_take_clip);
69 AVSC_DECLARE_FUNC(avs_bits_per_pixel);
70 AVSC_DECLARE_FUNC(avs_get_height_p);
71 AVSC_DECLARE_FUNC(avs_get_pitch_p);
72 AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
73 AVSC_DECLARE_FUNC(avs_get_row_size_p);
74 AVSC_DECLARE_FUNC(avs_is_yv24);
75 AVSC_DECLARE_FUNC(avs_is_yv16);
76 AVSC_DECLARE_FUNC(avs_is_yv411);
77 AVSC_DECLARE_FUNC(avs_is_y8);
79 #undef AVSC_DECLARE_FUNC
82 typedef struct AviSynthContext {
83 AVS_ScriptEnvironment *env;
85 const AVS_VideoInfo *vi;
87 /* avisynth_read_packet_video() iterates over this. */
97 /* Linked list pointers. */
98 struct AviSynthContext *next;
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,
106 /* A conflict between C++ global objects, atexit, and dynamic loading requires
107 * us to register our own atexit handler to prevent double freeing. */
108 static AviSynthLibrary avs_library;
109 static int avs_atexit_called = 0;
111 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
112 static AviSynthContext *avs_ctx_list = NULL;
114 static av_cold void avisynth_atexit_handler(void);
116 static av_cold int avisynth_load_library(void)
118 avs_library.library = LoadLibrary(AVISYNTH_LIB);
119 if (!avs_library.library)
120 return AVERROR_UNKNOWN;
122 #define LOAD_AVS_FUNC(name, continue_on_fail) \
124 (void *)GetProcAddress(avs_library.library, #name); \
125 if (!continue_on_fail && !avs_library.name) \
128 LOAD_AVS_FUNC(avs_bit_blt, 0);
129 LOAD_AVS_FUNC(avs_clip_get_error, 0);
130 LOAD_AVS_FUNC(avs_create_script_environment, 0);
131 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
132 LOAD_AVS_FUNC(avs_get_audio, 0);
133 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
134 LOAD_AVS_FUNC(avs_get_frame, 0);
135 LOAD_AVS_FUNC(avs_get_version, 0);
136 LOAD_AVS_FUNC(avs_get_video_info, 0);
137 LOAD_AVS_FUNC(avs_invoke, 0);
138 LOAD_AVS_FUNC(avs_release_clip, 0);
139 LOAD_AVS_FUNC(avs_release_value, 0);
140 LOAD_AVS_FUNC(avs_release_video_frame, 0);
141 LOAD_AVS_FUNC(avs_take_clip, 0);
142 #ifdef USING_AVISYNTH
143 LOAD_AVS_FUNC(avs_bits_per_pixel, 0);
144 LOAD_AVS_FUNC(avs_get_height_p, 0);
145 LOAD_AVS_FUNC(avs_get_pitch_p, 0);
146 LOAD_AVS_FUNC(avs_get_read_ptr_p, 0);
147 LOAD_AVS_FUNC(avs_get_row_size_p, 0);
148 LOAD_AVS_FUNC(avs_is_yv24, 0);
149 LOAD_AVS_FUNC(avs_is_yv16, 0);
150 LOAD_AVS_FUNC(avs_is_yv411, 0);
151 LOAD_AVS_FUNC(avs_is_y8, 0);
155 atexit(avisynth_atexit_handler);
159 FreeLibrary(avs_library.library);
160 return AVERROR_UNKNOWN;
163 /* Note that avisynth_context_create and avisynth_context_destroy
164 * do not allocate or free the actual context! That is taken care of
166 static av_cold int avisynth_context_create(AVFormatContext *s)
168 AviSynthContext *avs = s->priv_data;
171 if (!avs_library.library)
172 if (ret = avisynth_load_library())
175 avs->env = avs_library.avs_create_script_environment(3);
176 if (avs_library.avs_get_error) {
177 const char *error = avs_library.avs_get_error(avs->env);
179 av_log(s, AV_LOG_ERROR, "%s\n", error);
180 return AVERROR_UNKNOWN;
187 avs->next = avs_ctx_list;
194 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
196 if (avs_atexit_called)
199 if (avs == avs_ctx_list) {
200 avs_ctx_list = avs->next;
202 AviSynthContext *prev = avs_ctx_list;
203 while (prev->next != avs)
205 prev->next = avs->next;
209 avs_library.avs_release_clip(avs->clip);
213 avs_library.avs_delete_script_environment(avs->env);
218 static av_cold void avisynth_atexit_handler(void)
220 AviSynthContext *avs = avs_ctx_list;
223 AviSynthContext *next = avs->next;
224 avisynth_context_destroy(avs);
227 FreeLibrary(avs_library.library);
229 avs_atexit_called = 1;
232 /* Create AVStream from audio and video data. */
233 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
235 AviSynthContext *avs = s->priv_data;
236 int planar = 0; // 0: packed, 1: YUV, 2: Y8
238 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
239 st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;
240 st->codec->width = avs->vi->width;
241 st->codec->height = avs->vi->height;
243 st->time_base = (AVRational) { avs->vi->fps_denominator,
244 avs->vi->fps_numerator };
245 st->avg_frame_rate = (AVRational) { avs->vi->fps_numerator,
246 avs->vi->fps_denominator };
248 st->duration = avs->vi->num_frames;
249 st->nb_frames = avs->vi->num_frames;
251 switch (avs->vi->pixel_type) {
252 #ifdef USING_AVISYNTH
254 st->codec->pix_fmt = AV_PIX_FMT_YUV444P;
258 st->codec->pix_fmt = AV_PIX_FMT_YUV422P;
262 st->codec->pix_fmt = AV_PIX_FMT_YUV411P;
266 st->codec->pix_fmt = AV_PIX_FMT_GRAY8;
271 st->codec->pix_fmt = AV_PIX_FMT_BGR24;
274 st->codec->pix_fmt = AV_PIX_FMT_RGB32;
277 st->codec->pix_fmt = AV_PIX_FMT_YUYV422;
280 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
283 case AVS_CS_I420: // Is this even used anywhere?
284 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
288 av_log(s, AV_LOG_ERROR,
289 "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
291 return AVERROR_UNKNOWN;
297 avs->planes = avs_planes_grey;
301 avs->planes = avs_planes_yuv;
305 avs->planes = avs_planes_packed;
310 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
312 AviSynthContext *avs = s->priv_data;
314 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
315 st->codec->sample_rate = avs->vi->audio_samples_per_second;
316 st->codec->channels = avs->vi->nchannels;
317 st->time_base = (AVRational) { 1,
318 avs->vi->audio_samples_per_second };
319 st->duration = avs->vi->num_audio_samples;
321 switch (avs->vi->sample_type) {
322 case AVS_SAMPLE_INT8:
323 st->codec->codec_id = AV_CODEC_ID_PCM_U8;
325 case AVS_SAMPLE_INT16:
326 st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;
328 case AVS_SAMPLE_INT24:
329 st->codec->codec_id = AV_CODEC_ID_PCM_S24LE;
331 case AVS_SAMPLE_INT32:
332 st->codec->codec_id = AV_CODEC_ID_PCM_S32LE;
334 case AVS_SAMPLE_FLOAT:
335 st->codec->codec_id = AV_CODEC_ID_PCM_F32LE;
338 av_log(s, AV_LOG_ERROR,
339 "unknown AviSynth sample type %d\n", avs->vi->sample_type);
341 return AVERROR_UNKNOWN;
346 static int avisynth_create_stream(AVFormatContext *s)
348 AviSynthContext *avs = s->priv_data;
353 if (avs_has_video(avs->vi)) {
354 st = avformat_new_stream(s, NULL);
356 return AVERROR_UNKNOWN;
358 if (ret = avisynth_create_stream_video(s, st))
361 if (avs_has_audio(avs->vi)) {
362 st = avformat_new_stream(s, NULL);
364 return AVERROR_UNKNOWN;
366 if (ret = avisynth_create_stream_audio(s, st))
372 static int avisynth_open_file(AVFormatContext *s)
374 AviSynthContext *avs = s->priv_data;
377 #ifdef USING_AVISYNTH
378 char filename_ansi[MAX_PATH * 4];
379 wchar_t filename_wc[MAX_PATH * 4];
382 if (ret = avisynth_context_create(s))
385 #ifdef USING_AVISYNTH
386 /* Convert UTF-8 to ANSI code page */
387 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
388 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
389 MAX_PATH * 4, NULL, NULL);
390 arg = avs_new_value_string(filename_ansi);
392 arg = avs_new_value_string(s->filename);
394 val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
395 if (avs_is_error(val)) {
396 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
397 ret = AVERROR_UNKNOWN;
400 if (!avs_is_clip(val)) {
401 av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
402 ret = AVERROR_UNKNOWN;
406 avs->clip = avs_library.avs_take_clip(val, avs->env);
407 avs->vi = avs_library.avs_get_video_info(avs->clip);
409 /* Release the AVS_Value as it will go out of scope. */
410 avs_library.avs_release_value(val);
412 if (ret = avisynth_create_stream(s))
418 avisynth_context_destroy(avs);
422 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
423 AVPacket *pkt, int *discard)
425 AviSynthContext *avs = s->priv_data;
428 avs->curr_stream %= s->nb_streams;
430 *st = s->streams[avs->curr_stream];
431 if ((*st)->discard == AVDISCARD_ALL)
439 /* Copy AviSynth clip data into an AVPacket. */
440 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
443 AviSynthContext *avs = s->priv_data;
444 AVS_VideoFrame *frame;
445 unsigned char *dst_p;
446 const unsigned char *src_p;
447 int n, i, plane, rowsize, planeheight, pitch, bits;
450 if (avs->curr_frame >= avs->vi->num_frames)
453 /* This must happen even if the stream is discarded to prevent desync. */
454 n = avs->curr_frame++;
458 #ifdef USING_AVISYNTH
459 /* Define the bpp values for the new AviSynth 2.6 colorspaces.
460 * Since AvxSynth doesn't have these functions, special-case
461 * it in order to avoid implicit declaration errors. */
463 if (avs_library.avs_is_yv24(avs->vi))
465 else if (avs_library.avs_is_yv16(avs->vi))
467 else if (avs_library.avs_is_yv411(avs->vi))
469 else if (avs_library.avs_is_y8(avs->vi))
472 bits = avs_library.avs_bits_per_pixel(avs->vi);
474 bits = avs_bits_per_pixel(avs->vi);
477 /* Without the cast to int64_t, calculation overflows at about 9k x 9k
479 pkt->size = (((int64_t)avs->vi->width *
480 (int64_t)avs->vi->height) * bits) / 8;
482 return AVERROR_UNKNOWN;
484 if (av_new_packet(pkt, pkt->size) < 0)
485 return AVERROR(ENOMEM);
490 pkt->stream_index = avs->curr_stream;
492 frame = avs_library.avs_get_frame(avs->clip, n);
493 error = avs_library.avs_clip_get_error(avs->clip);
495 av_log(s, AV_LOG_ERROR, "%s\n", error);
497 av_packet_unref(pkt);
498 return AVERROR_UNKNOWN;
502 for (i = 0; i < avs->n_planes; i++) {
503 plane = avs->planes[i];
504 #ifdef USING_AVISYNTH
505 src_p = avs_library.avs_get_read_ptr_p(frame, plane);
506 pitch = avs_library.avs_get_pitch_p(frame, plane);
508 if (avs_library.avs_get_version(avs->clip) == 3) {
509 rowsize = avs_get_row_size_p_25(frame, plane);
510 planeheight = avs_get_height_p_25(frame, plane);
512 rowsize = avs_library.avs_get_row_size_p(frame, plane);
513 planeheight = avs_library.avs_get_height_p(frame, plane);
516 src_p = avs_get_read_ptr_p(frame, plane);
517 pitch = avs_get_pitch_p(frame, plane);
519 rowsize = avs_get_row_size_p(frame, plane);
520 planeheight = avs_get_height_p(frame, plane);
523 /* Flip RGB video. */
524 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
525 src_p = src_p + (planeheight - 1) * pitch;
529 avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
530 rowsize, planeheight);
531 dst_p += rowsize * planeheight;
534 avs_library.avs_release_video_frame(frame);
538 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
541 AviSynthContext *avs = s->priv_data;
542 AVRational fps, samplerate;
547 if (avs->curr_sample >= avs->vi->num_audio_samples)
550 fps.num = avs->vi->fps_numerator;
551 fps.den = avs->vi->fps_denominator;
552 samplerate.num = avs->vi->audio_samples_per_second;
555 if (avs_has_video(avs->vi)) {
556 if (avs->curr_frame < avs->vi->num_frames)
557 samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
560 samples = av_rescale_q(1, samplerate, fps);
565 /* After seeking, audio may catch up with video. */
572 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
573 samples = avs->vi->num_audio_samples - avs->curr_sample;
575 /* This must happen even if the stream is discarded to prevent desync. */
576 n = avs->curr_sample;
577 avs->curr_sample += samples;
581 pkt->size = avs_bytes_per_channel_sample(avs->vi) *
582 samples * avs->vi->nchannels;
584 return AVERROR_UNKNOWN;
586 if (av_new_packet(pkt, pkt->size) < 0)
587 return AVERROR(ENOMEM);
591 pkt->duration = samples;
592 pkt->stream_index = avs->curr_stream;
594 avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
595 error = avs_library.avs_clip_get_error(avs->clip);
597 av_log(s, AV_LOG_ERROR, "%s\n", error);
599 av_packet_unref(pkt);
600 return AVERROR_UNKNOWN;
605 static av_cold int avisynth_read_header(AVFormatContext *s)
609 // Calling library must implement a lock for thread-safe opens.
610 if (ret = avpriv_lock_avformat())
613 if (ret = avisynth_open_file(s)) {
614 avpriv_unlock_avformat();
618 avpriv_unlock_avformat();
622 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
624 AviSynthContext *avs = s->priv_data;
630 return AVERROR_UNKNOWN;
632 /* If either stream reaches EOF, try to read the other one before
634 avisynth_next_stream(s, &st, pkt, &discard);
635 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
636 ret = avisynth_read_packet_video(s, pkt, discard);
637 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
638 avisynth_next_stream(s, &st, pkt, &discard);
639 return avisynth_read_packet_audio(s, pkt, discard);
642 ret = avisynth_read_packet_audio(s, pkt, discard);
643 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
644 avisynth_next_stream(s, &st, pkt, &discard);
645 return avisynth_read_packet_video(s, pkt, discard);
652 static av_cold int avisynth_read_close(AVFormatContext *s)
654 if (avpriv_lock_avformat())
655 return AVERROR_UNKNOWN;
657 avisynth_context_destroy(s->priv_data);
658 avpriv_unlock_avformat();
662 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
663 int64_t timestamp, int flags)
665 AviSynthContext *avs = s->priv_data;
667 AVRational fps, samplerate;
670 return AVERROR_UNKNOWN;
672 fps = (AVRational) { avs->vi->fps_numerator,
673 avs->vi->fps_denominator };
674 samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
676 st = s->streams[stream_index];
677 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
678 /* AviSynth frame counts are signed int. */
679 if ((timestamp >= avs->vi->num_frames) ||
680 (timestamp > INT_MAX) ||
683 avs->curr_frame = timestamp;
684 if (avs_has_audio(avs->vi))
685 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
687 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
689 /* Force frame granularity for seeking. */
690 if (avs_has_video(avs->vi)) {
691 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
692 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
694 avs->curr_sample = timestamp;
701 AVInputFormat ff_avisynth_demuxer = {
703 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
704 .priv_data_size = sizeof(AviSynthContext),
705 .read_header = avisynth_read_header,
706 .read_packet = avisynth_read_packet,
707 .read_close = avisynth_read_close,
708 .read_seek = avisynth_read_seek,