2 * AviSynth/AvxSynth support
3 * Copyright (c) 2012 AvxSynth Team
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/internal.h"
23 #include "libavcodec/internal.h"
28 /* Enable function pointer definitions for runtime loading. */
29 #define AVSC_NO_DECLSPEC
31 /* Platform-specific directives for AviSynth vs AvxSynth. */
35 #include <avisynth/avisynth_c.h>
36 #define AVISYNTH_LIB "avisynth"
37 #define USING_AVISYNTH
40 #include <avxsynth/avxsynth_c.h>
41 #define AVISYNTH_NAME "libavxsynth"
42 #define AVISYNTH_LIB AVISYNTH_NAME SLIBSUF
44 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_LOCAL)
45 #define GetProcAddress dlsym
46 #define FreeLibrary dlclose
49 typedef struct AviSynthLibrary {
51 #define AVSC_DECLARE_FUNC(name) name ## _func name
52 AVSC_DECLARE_FUNC(avs_bit_blt);
53 AVSC_DECLARE_FUNC(avs_clip_get_error);
54 AVSC_DECLARE_FUNC(avs_create_script_environment);
55 AVSC_DECLARE_FUNC(avs_delete_script_environment);
56 AVSC_DECLARE_FUNC(avs_get_audio);
57 AVSC_DECLARE_FUNC(avs_get_error);
58 AVSC_DECLARE_FUNC(avs_get_frame);
59 AVSC_DECLARE_FUNC(avs_get_version);
60 AVSC_DECLARE_FUNC(avs_get_video_info);
61 AVSC_DECLARE_FUNC(avs_invoke);
62 AVSC_DECLARE_FUNC(avs_release_clip);
63 AVSC_DECLARE_FUNC(avs_release_value);
64 AVSC_DECLARE_FUNC(avs_release_video_frame);
65 AVSC_DECLARE_FUNC(avs_take_clip);
67 AVSC_DECLARE_FUNC(avs_bits_per_pixel);
68 AVSC_DECLARE_FUNC(avs_get_height_p);
69 AVSC_DECLARE_FUNC(avs_get_pitch_p);
70 AVSC_DECLARE_FUNC(avs_get_read_ptr_p);
71 AVSC_DECLARE_FUNC(avs_get_row_size_p);
73 #undef AVSC_DECLARE_FUNC
76 typedef struct AviSynthContext {
77 AVS_ScriptEnvironment *env;
79 const AVS_VideoInfo *vi;
81 /* avisynth_read_packet_video() iterates over this. */
91 /* Linked list pointers. */
92 struct AviSynthContext *next;
95 static const int avs_planes_packed[1] = { 0 };
96 static const int avs_planes_grey[1] = { AVS_PLANAR_Y };
97 static const int avs_planes_yuv[3] = { AVS_PLANAR_Y, AVS_PLANAR_U,
100 /* A conflict between C++ global objects, atexit, and dynamic loading requires
101 * us to register our own atexit handler to prevent double freeing. */
102 static AviSynthLibrary avs_library;
103 static int avs_atexit_called = 0;
105 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
106 static AviSynthContext *avs_ctx_list = NULL;
108 static av_cold void avisynth_atexit_handler(void);
110 static av_cold int avisynth_load_library(void)
112 avs_library.library = LoadLibrary(AVISYNTH_LIB);
113 if (!avs_library.library)
114 return AVERROR_UNKNOWN;
116 #define LOAD_AVS_FUNC(name, continue_on_fail) \
117 avs_library.name = GetProcAddress(avs_library.library, #name); \
118 if (!continue_on_fail && !avs_library.name) \
121 LOAD_AVS_FUNC(avs_bit_blt, 0);
122 LOAD_AVS_FUNC(avs_clip_get_error, 0);
123 LOAD_AVS_FUNC(avs_create_script_environment, 0);
124 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
125 LOAD_AVS_FUNC(avs_get_audio, 0);
126 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
127 LOAD_AVS_FUNC(avs_get_frame, 0);
128 LOAD_AVS_FUNC(avs_get_version, 0);
129 LOAD_AVS_FUNC(avs_get_video_info, 0);
130 LOAD_AVS_FUNC(avs_invoke, 0);
131 LOAD_AVS_FUNC(avs_release_clip, 0);
132 LOAD_AVS_FUNC(avs_release_value, 0);
133 LOAD_AVS_FUNC(avs_release_video_frame, 0);
134 LOAD_AVS_FUNC(avs_take_clip, 0);
135 #ifdef USING_AVISYNTH
136 LOAD_AVS_FUNC(avs_bits_per_pixel, 1);
137 LOAD_AVS_FUNC(avs_get_height_p, 1);
138 LOAD_AVS_FUNC(avs_get_pitch_p, 1);
139 LOAD_AVS_FUNC(avs_get_read_ptr_p, 1);
140 LOAD_AVS_FUNC(avs_get_row_size_p, 1);
144 atexit(avisynth_atexit_handler);
148 FreeLibrary(avs_library.library);
149 return AVERROR_UNKNOWN;
152 /* Note that avisynth_context_create and avisynth_context_destroy
153 * do not allocate or free the actual context! That is taken care of
155 static av_cold int avisynth_context_create(AVFormatContext *s)
157 AviSynthContext *avs = s->priv_data;
160 if (!avs_library.library)
161 if (ret = avisynth_load_library())
164 avs->env = avs_library.avs_create_script_environment(3);
165 if (avs_library.avs_get_error) {
166 const char *error = avs_library.avs_get_error(avs->env);
168 av_log(s, AV_LOG_ERROR, "%s\n", error);
169 return AVERROR_UNKNOWN;
176 avs->next = avs_ctx_list;
183 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
185 if (avs_atexit_called)
188 if (avs == avs_ctx_list) {
189 avs_ctx_list = avs->next;
191 AviSynthContext *prev = avs_ctx_list;
192 while (prev->next != avs)
194 prev->next = avs->next;
198 avs_library.avs_release_clip(avs->clip);
202 avs_library.avs_delete_script_environment(avs->env);
207 static av_cold void avisynth_atexit_handler(void)
209 AviSynthContext *avs = avs_ctx_list;
212 AviSynthContext *next = avs->next;
213 avisynth_context_destroy(avs);
216 FreeLibrary(avs_library.library);
218 avs_atexit_called = 1;
221 /* Create AVStream from audio and video data. */
222 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
224 AviSynthContext *avs = s->priv_data;
225 int planar = 0; // 0: packed, 1: YUV, 2: Y8
227 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
228 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
229 st->codecpar->width = avs->vi->width;
230 st->codecpar->height = avs->vi->height;
232 st->avg_frame_rate = (AVRational) { avs->vi->fps_numerator,
233 avs->vi->fps_denominator };
235 st->duration = avs->vi->num_frames;
236 st->nb_frames = avs->vi->num_frames;
237 avpriv_set_pts_info(st, 32, avs->vi->fps_denominator, avs->vi->fps_numerator);
239 switch (avs->vi->pixel_type) {
240 #ifdef USING_AVISYNTH
242 st->codecpar->format = AV_PIX_FMT_YUV444P;
246 st->codecpar->format = AV_PIX_FMT_YUV422P;
250 st->codecpar->format = AV_PIX_FMT_YUV411P;
254 st->codecpar->format = AV_PIX_FMT_GRAY8;
259 st->codecpar->format = AV_PIX_FMT_BGR24;
262 st->codecpar->format = AV_PIX_FMT_RGB32;
265 st->codecpar->format = AV_PIX_FMT_YUYV422;
268 st->codecpar->format = AV_PIX_FMT_YUV420P;
271 case AVS_CS_I420: // Is this even used anywhere?
272 st->codecpar->format = AV_PIX_FMT_YUV420P;
276 av_log(s, AV_LOG_ERROR,
277 "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
279 return AVERROR_UNKNOWN;
285 avs->planes = avs_planes_grey;
289 avs->planes = avs_planes_yuv;
293 avs->planes = avs_planes_packed;
298 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
300 AviSynthContext *avs = s->priv_data;
302 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
303 st->codecpar->sample_rate = avs->vi->audio_samples_per_second;
304 st->codecpar->channels = avs->vi->nchannels;
305 st->duration = avs->vi->num_audio_samples;
306 avpriv_set_pts_info(st, 64, 1, avs->vi->audio_samples_per_second);
308 switch (avs->vi->sample_type) {
309 case AVS_SAMPLE_INT8:
310 st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
312 case AVS_SAMPLE_INT16:
313 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
315 case AVS_SAMPLE_INT24:
316 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
318 case AVS_SAMPLE_INT32:
319 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
321 case AVS_SAMPLE_FLOAT:
322 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
325 av_log(s, AV_LOG_ERROR,
326 "unknown AviSynth sample type %d\n", avs->vi->sample_type);
328 return AVERROR_UNKNOWN;
333 static int avisynth_create_stream(AVFormatContext *s)
335 AviSynthContext *avs = s->priv_data;
340 if (avs_has_video(avs->vi)) {
341 st = avformat_new_stream(s, NULL);
343 return AVERROR_UNKNOWN;
345 if (ret = avisynth_create_stream_video(s, st))
348 if (avs_has_audio(avs->vi)) {
349 st = avformat_new_stream(s, NULL);
351 return AVERROR_UNKNOWN;
353 if (ret = avisynth_create_stream_audio(s, st))
359 static int avisynth_open_file(AVFormatContext *s)
361 AviSynthContext *avs = s->priv_data;
364 #ifdef USING_AVISYNTH
365 char filename_ansi[MAX_PATH * 4];
366 wchar_t filename_wc[MAX_PATH * 4];
369 if (ret = avisynth_context_create(s))
372 #ifdef USING_AVISYNTH
373 /* Convert UTF-8 to ANSI code page */
374 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
375 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
376 MAX_PATH * 4, NULL, NULL);
377 arg = avs_new_value_string(filename_ansi);
379 arg = avs_new_value_string(s->filename);
381 val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
382 if (avs_is_error(val)) {
383 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
384 ret = AVERROR_UNKNOWN;
387 if (!avs_is_clip(val)) {
388 av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
389 ret = AVERROR_UNKNOWN;
393 avs->clip = avs_library.avs_take_clip(val, avs->env);
394 avs->vi = avs_library.avs_get_video_info(avs->clip);
396 #ifdef USING_AVISYNTH
397 /* On Windows, libav supports AviSynth interface version 6 or higher.
398 * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
399 * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
400 * as interface version 3 like 2.5.8, this needs to be special-cased. */
402 if (avs_library.avs_get_version(avs->clip) < 6) {
403 av_log(s, AV_LOG_ERROR,
404 "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
405 ret = AVERROR_UNKNOWN;
410 /* Release the AVS_Value as it will go out of scope. */
411 avs_library.avs_release_value(val);
413 if (ret = avisynth_create_stream(s))
419 avisynth_context_destroy(avs);
423 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
424 AVPacket *pkt, int *discard)
426 AviSynthContext *avs = s->priv_data;
429 avs->curr_stream %= s->nb_streams;
431 *st = s->streams[avs->curr_stream];
432 if ((*st)->discard == AVDISCARD_ALL)
440 /* Copy AviSynth clip data into an AVPacket. */
441 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
444 AviSynthContext *avs = s->priv_data;
445 AVS_VideoFrame *frame;
446 unsigned char *dst_p;
447 const unsigned char *src_p;
448 int n, i, plane, rowsize, planeheight, pitch, bits;
451 if (avs->curr_frame >= avs->vi->num_frames)
454 /* This must happen even if the stream is discarded to prevent desync. */
455 n = avs->curr_frame++;
459 #ifdef USING_AVISYNTH
460 /* avs_bits_per_pixel changed to AVSC_API with AviSynth 2.6, which
461 * requires going through avs_library, while AvxSynth has it under
462 * the older AVSC_INLINE type, so special-case this. */
464 bits = avs_library.avs_bits_per_pixel(avs->vi);
466 bits = avs_bits_per_pixel(avs->vi);
469 /* Without the cast to int64_t, calculation overflows at about 9k x 9k
471 pkt->size = (((int64_t)avs->vi->width *
472 (int64_t)avs->vi->height) * bits) / 8;
474 return AVERROR_UNKNOWN;
476 if (av_new_packet(pkt, pkt->size) < 0)
477 return AVERROR(ENOMEM);
482 pkt->stream_index = avs->curr_stream;
484 frame = avs_library.avs_get_frame(avs->clip, n);
485 error = avs_library.avs_clip_get_error(avs->clip);
487 av_log(s, AV_LOG_ERROR, "%s\n", error);
489 av_packet_unref(pkt);
490 return AVERROR_UNKNOWN;
494 for (i = 0; i < avs->n_planes; i++) {
495 plane = avs->planes[i];
496 #ifdef USING_AVISYNTH
497 src_p = avs_library.avs_get_read_ptr_p(frame, plane);
498 pitch = avs_library.avs_get_pitch_p(frame, plane);
500 rowsize = avs_library.avs_get_row_size_p(frame, plane);
501 planeheight = avs_library.avs_get_height_p(frame, plane);
503 src_p = avs_get_read_ptr_p(frame, plane);
504 pitch = avs_get_pitch_p(frame, plane);
506 rowsize = avs_get_row_size_p(frame, plane);
507 planeheight = avs_get_height_p(frame, plane);
510 /* Flip RGB video. */
511 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
512 src_p = src_p + (planeheight - 1) * pitch;
516 avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
517 rowsize, planeheight);
518 dst_p += rowsize * planeheight;
521 avs_library.avs_release_video_frame(frame);
525 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
528 AviSynthContext *avs = s->priv_data;
529 AVRational fps, samplerate;
534 if (avs->curr_sample >= avs->vi->num_audio_samples)
537 fps.num = avs->vi->fps_numerator;
538 fps.den = avs->vi->fps_denominator;
539 samplerate.num = avs->vi->audio_samples_per_second;
542 if (avs_has_video(avs->vi)) {
543 if (avs->curr_frame < avs->vi->num_frames)
544 samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
547 samples = av_rescale_q(1, samplerate, fps);
552 /* After seeking, audio may catch up with video. */
559 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
560 samples = avs->vi->num_audio_samples - avs->curr_sample;
562 /* This must happen even if the stream is discarded to prevent desync. */
563 n = avs->curr_sample;
564 avs->curr_sample += samples;
568 pkt->size = avs_bytes_per_channel_sample(avs->vi) *
569 samples * avs->vi->nchannels;
571 return AVERROR_UNKNOWN;
573 if (av_new_packet(pkt, pkt->size) < 0)
574 return AVERROR(ENOMEM);
578 pkt->duration = samples;
579 pkt->stream_index = avs->curr_stream;
581 avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
582 error = avs_library.avs_clip_get_error(avs->clip);
584 av_log(s, AV_LOG_ERROR, "%s\n", error);
586 av_packet_unref(pkt);
587 return AVERROR_UNKNOWN;
592 static av_cold int avisynth_read_header(AVFormatContext *s)
596 // Calling library must implement a lock for thread-safe opens.
597 if (ret = avpriv_lock_avformat())
600 if (ret = avisynth_open_file(s)) {
601 avpriv_unlock_avformat();
605 avpriv_unlock_avformat();
609 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
611 AviSynthContext *avs = s->priv_data;
617 return AVERROR_UNKNOWN;
619 /* If either stream reaches EOF, try to read the other one before
621 avisynth_next_stream(s, &st, pkt, &discard);
622 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
623 ret = avisynth_read_packet_video(s, pkt, discard);
624 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
625 avisynth_next_stream(s, &st, pkt, &discard);
626 return avisynth_read_packet_audio(s, pkt, discard);
629 ret = avisynth_read_packet_audio(s, pkt, discard);
630 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
631 avisynth_next_stream(s, &st, pkt, &discard);
632 return avisynth_read_packet_video(s, pkt, discard);
639 static av_cold int avisynth_read_close(AVFormatContext *s)
641 if (avpriv_lock_avformat())
642 return AVERROR_UNKNOWN;
644 avisynth_context_destroy(s->priv_data);
645 avpriv_unlock_avformat();
649 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
650 int64_t timestamp, int flags)
652 AviSynthContext *avs = s->priv_data;
654 AVRational fps, samplerate;
657 return AVERROR_UNKNOWN;
659 fps = (AVRational) { avs->vi->fps_numerator,
660 avs->vi->fps_denominator };
661 samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
663 st = s->streams[stream_index];
664 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
665 /* AviSynth frame counts are signed int. */
666 if ((timestamp >= avs->vi->num_frames) ||
667 (timestamp > INT_MAX) ||
670 avs->curr_frame = timestamp;
671 if (avs_has_audio(avs->vi))
672 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
674 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
676 /* Force frame granularity for seeking. */
677 if (avs_has_video(avs->vi)) {
678 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
679 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
681 avs->curr_sample = timestamp;
688 AVInputFormat ff_avisynth_demuxer = {
690 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
691 .priv_data_size = sizeof(AviSynthContext),
692 .read_header = avisynth_read_header,
693 .read_packet = avisynth_read_packet,
694 .read_close = avisynth_read_close,
695 .read_seek = avisynth_read_seek,