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);
72 AVSC_DECLARE_FUNC(avs_is_yv24);
73 AVSC_DECLARE_FUNC(avs_is_yv16);
74 AVSC_DECLARE_FUNC(avs_is_yv411);
75 AVSC_DECLARE_FUNC(avs_is_y8);
77 #undef AVSC_DECLARE_FUNC
80 typedef struct AviSynthContext {
81 AVS_ScriptEnvironment *env;
83 const AVS_VideoInfo *vi;
85 /* avisynth_read_packet_video() iterates over this. */
95 /* Linked list pointers. */
96 struct AviSynthContext *next;
99 static const int avs_planes_packed[1] = { 0 };
100 static const int avs_planes_grey[1] = { AVS_PLANAR_Y };
101 static const int avs_planes_yuv[3] = { AVS_PLANAR_Y, AVS_PLANAR_U,
104 /* A conflict between C++ global objects, atexit, and dynamic loading requires
105 * us to register our own atexit handler to prevent double freeing. */
106 static AviSynthLibrary avs_library;
107 static int avs_atexit_called = 0;
109 /* Linked list of AviSynthContexts. An atexit handler destroys this list. */
110 static AviSynthContext *avs_ctx_list = NULL;
112 static av_cold void avisynth_atexit_handler(void);
114 static av_cold int avisynth_load_library(void)
116 avs_library.library = LoadLibrary(AVISYNTH_LIB);
117 if (!avs_library.library)
118 return AVERROR_UNKNOWN;
120 #define LOAD_AVS_FUNC(name, continue_on_fail) \
122 (void *)GetProcAddress(avs_library.library, #name); \
123 if (!continue_on_fail && !avs_library.name) \
126 LOAD_AVS_FUNC(avs_bit_blt, 0);
127 LOAD_AVS_FUNC(avs_clip_get_error, 0);
128 LOAD_AVS_FUNC(avs_create_script_environment, 0);
129 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
130 LOAD_AVS_FUNC(avs_get_audio, 0);
131 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
132 LOAD_AVS_FUNC(avs_get_frame, 0);
133 LOAD_AVS_FUNC(avs_get_version, 0);
134 LOAD_AVS_FUNC(avs_get_video_info, 0);
135 LOAD_AVS_FUNC(avs_invoke, 0);
136 LOAD_AVS_FUNC(avs_release_clip, 0);
137 LOAD_AVS_FUNC(avs_release_value, 0);
138 LOAD_AVS_FUNC(avs_release_video_frame, 0);
139 LOAD_AVS_FUNC(avs_take_clip, 0);
140 #ifdef USING_AVISYNTH
141 LOAD_AVS_FUNC(avs_bits_per_pixel, 1);
142 LOAD_AVS_FUNC(avs_get_height_p, 1);
143 LOAD_AVS_FUNC(avs_get_pitch_p, 1);
144 LOAD_AVS_FUNC(avs_get_read_ptr_p, 1);
145 LOAD_AVS_FUNC(avs_get_row_size_p, 1);
146 LOAD_AVS_FUNC(avs_is_yv24, 1);
147 LOAD_AVS_FUNC(avs_is_yv16, 1);
148 LOAD_AVS_FUNC(avs_is_yv411, 1);
149 LOAD_AVS_FUNC(avs_is_y8, 1);
153 atexit(avisynth_atexit_handler);
157 FreeLibrary(avs_library.library);
158 return AVERROR_UNKNOWN;
161 /* Note that avisynth_context_create and avisynth_context_destroy
162 * do not allocate or free the actual context! That is taken care of
164 static av_cold int avisynth_context_create(AVFormatContext *s)
166 AviSynthContext *avs = s->priv_data;
169 if (!avs_library.library)
170 if (ret = avisynth_load_library())
173 avs->env = avs_library.avs_create_script_environment(3);
174 if (avs_library.avs_get_error) {
175 const char *error = avs_library.avs_get_error(avs->env);
177 av_log(s, AV_LOG_ERROR, "%s\n", error);
178 return AVERROR_UNKNOWN;
185 avs->next = avs_ctx_list;
192 static av_cold void avisynth_context_destroy(AviSynthContext *avs)
194 if (avs_atexit_called)
197 if (avs == avs_ctx_list) {
198 avs_ctx_list = avs->next;
200 AviSynthContext *prev = avs_ctx_list;
201 while (prev->next != avs)
203 prev->next = avs->next;
207 avs_library.avs_release_clip(avs->clip);
211 avs_library.avs_delete_script_environment(avs->env);
216 static av_cold void avisynth_atexit_handler(void)
218 AviSynthContext *avs = avs_ctx_list;
221 AviSynthContext *next = avs->next;
222 avisynth_context_destroy(avs);
225 FreeLibrary(avs_library.library);
227 avs_atexit_called = 1;
230 /* Create AVStream from audio and video data. */
231 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st)
233 AviSynthContext *avs = s->priv_data;
234 int planar = 0; // 0: packed, 1: YUV, 2: Y8
236 st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
237 st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
238 st->codecpar->width = avs->vi->width;
239 st->codecpar->height = avs->vi->height;
241 st->time_base = (AVRational) { avs->vi->fps_denominator,
242 avs->vi->fps_numerator };
243 st->avg_frame_rate = (AVRational) { avs->vi->fps_numerator,
244 avs->vi->fps_denominator };
246 st->duration = avs->vi->num_frames;
247 st->nb_frames = avs->vi->num_frames;
249 switch (avs->vi->pixel_type) {
250 #ifdef USING_AVISYNTH
252 st->codecpar->format = AV_PIX_FMT_YUV444P;
256 st->codecpar->format = AV_PIX_FMT_YUV422P;
260 st->codecpar->format = AV_PIX_FMT_YUV411P;
264 st->codecpar->format = AV_PIX_FMT_GRAY8;
269 st->codecpar->format = AV_PIX_FMT_BGR24;
272 st->codecpar->format = AV_PIX_FMT_RGB32;
275 st->codecpar->format = AV_PIX_FMT_YUYV422;
278 st->codecpar->format = AV_PIX_FMT_YUV420P;
281 case AVS_CS_I420: // Is this even used anywhere?
282 st->codecpar->format = AV_PIX_FMT_YUV420P;
286 av_log(s, AV_LOG_ERROR,
287 "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
289 return AVERROR_UNKNOWN;
295 avs->planes = avs_planes_grey;
299 avs->planes = avs_planes_yuv;
303 avs->planes = avs_planes_packed;
308 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st)
310 AviSynthContext *avs = s->priv_data;
312 st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
313 st->codecpar->sample_rate = avs->vi->audio_samples_per_second;
314 st->codecpar->channels = avs->vi->nchannels;
315 st->time_base = (AVRational) { 1,
316 avs->vi->audio_samples_per_second };
317 st->duration = avs->vi->num_audio_samples;
319 switch (avs->vi->sample_type) {
320 case AVS_SAMPLE_INT8:
321 st->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
323 case AVS_SAMPLE_INT16:
324 st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE;
326 case AVS_SAMPLE_INT24:
327 st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE;
329 case AVS_SAMPLE_INT32:
330 st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE;
332 case AVS_SAMPLE_FLOAT:
333 st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE;
336 av_log(s, AV_LOG_ERROR,
337 "unknown AviSynth sample type %d\n", avs->vi->sample_type);
339 return AVERROR_UNKNOWN;
344 static int avisynth_create_stream(AVFormatContext *s)
346 AviSynthContext *avs = s->priv_data;
351 if (avs_has_video(avs->vi)) {
352 st = avformat_new_stream(s, NULL);
354 return AVERROR_UNKNOWN;
356 if (ret = avisynth_create_stream_video(s, st))
359 if (avs_has_audio(avs->vi)) {
360 st = avformat_new_stream(s, NULL);
362 return AVERROR_UNKNOWN;
364 if (ret = avisynth_create_stream_audio(s, st))
370 static int avisynth_open_file(AVFormatContext *s)
372 AviSynthContext *avs = s->priv_data;
375 #ifdef USING_AVISYNTH
376 char filename_ansi[MAX_PATH * 4];
377 wchar_t filename_wc[MAX_PATH * 4];
380 if (ret = avisynth_context_create(s))
383 #ifdef USING_AVISYNTH
384 /* Convert UTF-8 to ANSI code page */
385 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
386 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi,
387 MAX_PATH * 4, NULL, NULL);
388 arg = avs_new_value_string(filename_ansi);
390 arg = avs_new_value_string(s->filename);
392 val = avs_library.avs_invoke(avs->env, "Import", arg, 0);
393 if (avs_is_error(val)) {
394 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
395 ret = AVERROR_UNKNOWN;
398 if (!avs_is_clip(val)) {
399 av_log(s, AV_LOG_ERROR, "AviSynth script did not return a clip\n");
400 ret = AVERROR_UNKNOWN;
404 avs->clip = avs_library.avs_take_clip(val, avs->env);
405 avs->vi = avs_library.avs_get_video_info(avs->clip);
407 #ifdef USING_AVISYNTH
408 /* On Windows, libav supports AviSynth interface version 6 or higher.
409 * This includes AviSynth 2.6 RC1 or higher, and AviSynth+ r1718 or higher,
410 * and excludes 2.5 and the 2.6 alphas. Since AvxSynth identifies itself
411 * as interface version 3 like 2.5.8, this needs to be special-cased. */
413 if (avs_library.avs_get_version(avs->clip) < 6) {
414 av_log(s, AV_LOG_ERROR,
415 "AviSynth version is too old. Please upgrade to either AviSynth 2.6 >= RC1 or AviSynth+ >= r1718.\n");
416 ret = AVERROR_UNKNOWN;
421 /* Release the AVS_Value as it will go out of scope. */
422 avs_library.avs_release_value(val);
424 if (ret = avisynth_create_stream(s))
430 avisynth_context_destroy(avs);
434 static void avisynth_next_stream(AVFormatContext *s, AVStream **st,
435 AVPacket *pkt, int *discard)
437 AviSynthContext *avs = s->priv_data;
440 avs->curr_stream %= s->nb_streams;
442 *st = s->streams[avs->curr_stream];
443 if ((*st)->discard == AVDISCARD_ALL)
451 /* Copy AviSynth clip data into an AVPacket. */
452 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt,
455 AviSynthContext *avs = s->priv_data;
456 AVS_VideoFrame *frame;
457 unsigned char *dst_p;
458 const unsigned char *src_p;
459 int n, i, plane, rowsize, planeheight, pitch, bits;
462 if (avs->curr_frame >= avs->vi->num_frames)
465 /* This must happen even if the stream is discarded to prevent desync. */
466 n = avs->curr_frame++;
470 #ifdef USING_AVISYNTH
471 /* Define the bpp values for the new AviSynth 2.6 colorspaces.
472 * Since AvxSynth doesn't have these functions, special-case
473 * it in order to avoid implicit declaration errors. */
475 if (avs_library.avs_is_yv24(avs->vi))
477 else if (avs_library.avs_is_yv16(avs->vi))
479 else if (avs_library.avs_is_yv411(avs->vi))
481 else if (avs_library.avs_is_y8(avs->vi))
484 bits = avs_library.avs_bits_per_pixel(avs->vi);
486 bits = avs_bits_per_pixel(avs->vi);
489 /* Without the cast to int64_t, calculation overflows at about 9k x 9k
491 pkt->size = (((int64_t)avs->vi->width *
492 (int64_t)avs->vi->height) * bits) / 8;
494 return AVERROR_UNKNOWN;
496 if (av_new_packet(pkt, pkt->size) < 0)
497 return AVERROR(ENOMEM);
502 pkt->stream_index = avs->curr_stream;
504 frame = avs_library.avs_get_frame(avs->clip, n);
505 error = avs_library.avs_clip_get_error(avs->clip);
507 av_log(s, AV_LOG_ERROR, "%s\n", error);
509 av_packet_unref(pkt);
510 return AVERROR_UNKNOWN;
514 for (i = 0; i < avs->n_planes; i++) {
515 plane = avs->planes[i];
516 #ifdef USING_AVISYNTH
517 src_p = avs_library.avs_get_read_ptr_p(frame, plane);
518 pitch = avs_library.avs_get_pitch_p(frame, plane);
520 rowsize = avs_library.avs_get_row_size_p(frame, plane);
521 planeheight = avs_library.avs_get_height_p(frame, plane);
523 src_p = avs_get_read_ptr_p(frame, plane);
524 pitch = avs_get_pitch_p(frame, plane);
526 rowsize = avs_get_row_size_p(frame, plane);
527 planeheight = avs_get_height_p(frame, plane);
530 /* Flip RGB video. */
531 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
532 src_p = src_p + (planeheight - 1) * pitch;
536 avs_library.avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch,
537 rowsize, planeheight);
538 dst_p += rowsize * planeheight;
541 avs_library.avs_release_video_frame(frame);
545 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt,
548 AviSynthContext *avs = s->priv_data;
549 AVRational fps, samplerate;
554 if (avs->curr_sample >= avs->vi->num_audio_samples)
557 fps.num = avs->vi->fps_numerator;
558 fps.den = avs->vi->fps_denominator;
559 samplerate.num = avs->vi->audio_samples_per_second;
562 if (avs_has_video(avs->vi)) {
563 if (avs->curr_frame < avs->vi->num_frames)
564 samples = av_rescale_q(avs->curr_frame, samplerate, fps) -
567 samples = av_rescale_q(1, samplerate, fps);
572 /* After seeking, audio may catch up with video. */
579 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
580 samples = avs->vi->num_audio_samples - avs->curr_sample;
582 /* This must happen even if the stream is discarded to prevent desync. */
583 n = avs->curr_sample;
584 avs->curr_sample += samples;
588 pkt->size = avs_bytes_per_channel_sample(avs->vi) *
589 samples * avs->vi->nchannels;
591 return AVERROR_UNKNOWN;
593 if (av_new_packet(pkt, pkt->size) < 0)
594 return AVERROR(ENOMEM);
598 pkt->duration = samples;
599 pkt->stream_index = avs->curr_stream;
601 avs_library.avs_get_audio(avs->clip, pkt->data, n, samples);
602 error = avs_library.avs_clip_get_error(avs->clip);
604 av_log(s, AV_LOG_ERROR, "%s\n", error);
606 av_packet_unref(pkt);
607 return AVERROR_UNKNOWN;
612 static av_cold int avisynth_read_header(AVFormatContext *s)
616 // Calling library must implement a lock for thread-safe opens.
617 if (ret = avpriv_lock_avformat())
620 if (ret = avisynth_open_file(s)) {
621 avpriv_unlock_avformat();
625 avpriv_unlock_avformat();
629 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt)
631 AviSynthContext *avs = s->priv_data;
637 return AVERROR_UNKNOWN;
639 /* If either stream reaches EOF, try to read the other one before
641 avisynth_next_stream(s, &st, pkt, &discard);
642 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
643 ret = avisynth_read_packet_video(s, pkt, discard);
644 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
645 avisynth_next_stream(s, &st, pkt, &discard);
646 return avisynth_read_packet_audio(s, pkt, discard);
649 ret = avisynth_read_packet_audio(s, pkt, discard);
650 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
651 avisynth_next_stream(s, &st, pkt, &discard);
652 return avisynth_read_packet_video(s, pkt, discard);
659 static av_cold int avisynth_read_close(AVFormatContext *s)
661 if (avpriv_lock_avformat())
662 return AVERROR_UNKNOWN;
664 avisynth_context_destroy(s->priv_data);
665 avpriv_unlock_avformat();
669 static int avisynth_read_seek(AVFormatContext *s, int stream_index,
670 int64_t timestamp, int flags)
672 AviSynthContext *avs = s->priv_data;
674 AVRational fps, samplerate;
677 return AVERROR_UNKNOWN;
679 fps = (AVRational) { avs->vi->fps_numerator,
680 avs->vi->fps_denominator };
681 samplerate = (AVRational) { avs->vi->audio_samples_per_second, 1 };
683 st = s->streams[stream_index];
684 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
685 /* AviSynth frame counts are signed int. */
686 if ((timestamp >= avs->vi->num_frames) ||
687 (timestamp > INT_MAX) ||
690 avs->curr_frame = timestamp;
691 if (avs_has_audio(avs->vi))
692 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
694 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
696 /* Force frame granularity for seeking. */
697 if (avs_has_video(avs->vi)) {
698 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
699 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
701 avs->curr_sample = timestamp;
708 AVInputFormat ff_avisynth_demuxer = {
710 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
711 .priv_data_size = sizeof(AviSynthContext),
712 .read_header = avisynth_read_header,
713 .read_packet = avisynth_read_packet,
714 .read_close = avisynth_read_close,
715 .read_seek = avisynth_read_seek,