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 #include "compat/avisynth/avisynth_c_25.h"
40 #define AVISYNTH_LIB "avisynth"
43 #include "compat/avisynth/avxsynth_c.h"
44 #if defined (__APPLE__)
45 #define AVISYNTH_LIB "libavxsynth.dylib"
47 #define AVISYNTH_LIB "libavxsynth.so"
50 #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
51 #define GetProcAddress dlsym
52 #define FreeLibrary dlclose
55 // AvxSynth doesn't have these colorspaces, so disable them
57 #define avs_is_yv24(vi) 0
58 #define avs_is_yv16(vi) 0
59 #define avs_is_yv411(vi) 0
60 #define avs_is_y8(vi) 0
65 #define AVSC_DECLARE_FUNC(name) name##_func name
66 AVSC_DECLARE_FUNC(avs_bit_blt);
67 AVSC_DECLARE_FUNC(avs_clip_get_error);
68 AVSC_DECLARE_FUNC(avs_create_script_environment);
69 AVSC_DECLARE_FUNC(avs_delete_script_environment);
70 AVSC_DECLARE_FUNC(avs_get_audio);
71 AVSC_DECLARE_FUNC(avs_get_error);
72 AVSC_DECLARE_FUNC(avs_get_frame);
73 AVSC_DECLARE_FUNC(avs_get_version);
74 AVSC_DECLARE_FUNC(avs_get_video_info);
75 AVSC_DECLARE_FUNC(avs_invoke);
76 AVSC_DECLARE_FUNC(avs_release_clip);
77 AVSC_DECLARE_FUNC(avs_release_value);
78 AVSC_DECLARE_FUNC(avs_release_video_frame);
79 AVSC_DECLARE_FUNC(avs_take_clip);
80 #undef AVSC_DECLARE_FUNC
83 struct AviSynthContext {
84 AVS_ScriptEnvironment *env;
86 const AVS_VideoInfo *vi;
88 // avisynth_read_packet_video() iterates over this.
98 // Linked list pointers.
99 struct AviSynthContext *next;
101 typedef struct AviSynthContext AviSynthContext;
103 static const int avs_planes_packed[1] = {0};
104 static const int avs_planes_grey[1] = {AVS_PLANAR_Y};
105 static const int avs_planes_yuv[3] = {AVS_PLANAR_Y, AVS_PLANAR_U, AVS_PLANAR_V};
107 // A conflict between C++ global objects, atexit, and dynamic loading requires
108 // us to register our own atexit handler to prevent double freeing.
109 static AviSynthLibrary *avs_library = NULL;
110 static int avs_atexit_called = 0;
112 // Linked list of AviSynthContexts. An atexit handler destroys this list.
113 static AviSynthContext *avs_ctx_list = NULL;
115 static av_cold void avisynth_atexit_handler(void);
117 static av_cold int avisynth_load_library(void) {
118 avs_library = av_mallocz(sizeof(AviSynthLibrary));
120 return AVERROR_UNKNOWN;
122 avs_library->library = LoadLibrary(AVISYNTH_LIB);
123 if (!avs_library->library)
126 #define LOAD_AVS_FUNC(name, continue_on_fail) \
128 avs_library->name = (void*)GetProcAddress(avs_library->library, #name); \
129 if(!continue_on_fail && !avs_library->name) \
132 LOAD_AVS_FUNC(avs_bit_blt, 0);
133 LOAD_AVS_FUNC(avs_clip_get_error, 0);
134 LOAD_AVS_FUNC(avs_create_script_environment, 0);
135 LOAD_AVS_FUNC(avs_delete_script_environment, 0);
136 LOAD_AVS_FUNC(avs_get_audio, 0);
137 LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
138 LOAD_AVS_FUNC(avs_get_frame, 0);
139 LOAD_AVS_FUNC(avs_get_version, 0);
140 LOAD_AVS_FUNC(avs_get_video_info, 0);
141 LOAD_AVS_FUNC(avs_invoke, 0);
142 LOAD_AVS_FUNC(avs_release_clip, 0);
143 LOAD_AVS_FUNC(avs_release_value, 0);
144 LOAD_AVS_FUNC(avs_release_video_frame, 0);
145 LOAD_AVS_FUNC(avs_take_clip, 0);
148 atexit(avisynth_atexit_handler);
152 FreeLibrary(avs_library->library);
154 av_freep(&avs_library);
155 return AVERROR_UNKNOWN;
158 // Note that avisynth_context_create and avisynth_context_destroy
159 // do not allocate or free the actual context! That is taken care of
161 static av_cold int avisynth_context_create(AVFormatContext *s) {
162 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
166 if (ret = avisynth_load_library())
170 avs->env = avs_library->avs_create_script_environment(3);
171 if (avs_library->avs_get_error) {
172 const char *error = avs_library->avs_get_error(avs->env);
174 av_log(s, AV_LOG_ERROR, "%s\n", error);
175 return AVERROR_UNKNOWN;
182 avs->next = avs_ctx_list;
189 static av_cold void avisynth_context_destroy(AviSynthContext *avs) {
190 if (avs_atexit_called)
193 if (avs == avs_ctx_list) {
194 avs_ctx_list = avs->next;
196 AviSynthContext *prev = avs_ctx_list;
197 while (prev->next != avs)
199 prev->next = avs->next;
203 avs_library->avs_release_clip(avs->clip);
207 avs_library->avs_delete_script_environment(avs->env);
212 static av_cold void avisynth_atexit_handler(void) {
213 AviSynthContext *avs = avs_ctx_list;
216 AviSynthContext *next = avs->next;
217 avisynth_context_destroy(avs);
220 FreeLibrary(avs_library->library);
221 av_freep(&avs_library);
223 avs_atexit_called = 1;
226 // Create AVStream from audio and video data.
227 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st) {
228 AviSynthContext *avs = s->priv_data;
229 int planar = 0; // 0: packed, 1: YUV, 2: Y8
231 st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
232 st->codec->codec_id = CODEC_ID_RAWVIDEO;
233 st->codec->width = avs->vi->width;
234 st->codec->height = avs->vi->height;
236 st->time_base = (AVRational) {avs->vi->fps_denominator, avs->vi->fps_numerator};
237 st->avg_frame_rate = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
239 st->duration = avs->vi->num_frames;
240 st->nb_frames = avs->vi->num_frames;
242 switch (avs->vi->pixel_type) {
245 st->codec->pix_fmt = AV_PIX_FMT_YUV444P;
249 st->codec->pix_fmt = AV_PIX_FMT_YUV422P;
253 st->codec->pix_fmt = AV_PIX_FMT_YUV411P;
257 st->codec->pix_fmt = AV_PIX_FMT_GRAY8;
262 st->codec->pix_fmt = AV_PIX_FMT_BGR24;
265 st->codec->pix_fmt = AV_PIX_FMT_RGB32;
268 st->codec->pix_fmt = AV_PIX_FMT_YUYV422;
271 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
274 case AVS_CS_I420: // Is this even used anywhere?
275 st->codec->pix_fmt = AV_PIX_FMT_YUV420P;
279 av_log(s, AV_LOG_ERROR, "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
281 return AVERROR_UNKNOWN;
287 avs->planes = avs_planes_grey;
291 avs->planes = avs_planes_yuv;
295 avs->planes = avs_planes_packed;
300 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st) {
301 AviSynthContext *avs = s->priv_data;
303 st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
304 st->codec->sample_rate = avs->vi->audio_samples_per_second;
305 st->codec->channels = avs->vi->nchannels;
306 st->time_base = (AVRational) {1, avs->vi->audio_samples_per_second};
308 switch (avs->vi->sample_type) {
309 case AVS_SAMPLE_INT8:
310 st->codec->codec_id = CODEC_ID_PCM_U8;
312 case AVS_SAMPLE_INT16:
313 st->codec->codec_id = CODEC_ID_PCM_S16LE;
315 case AVS_SAMPLE_INT24:
316 st->codec->codec_id = CODEC_ID_PCM_S24LE;
318 case AVS_SAMPLE_INT32:
319 st->codec->codec_id = CODEC_ID_PCM_S32LE;
321 case AVS_SAMPLE_FLOAT:
322 st->codec->codec_id = CODEC_ID_PCM_F32LE;
325 av_log(s, AV_LOG_ERROR, "unknown AviSynth sample type %d\n", avs->vi->sample_type);
327 return AVERROR_UNKNOWN;
332 static int avisynth_create_stream(AVFormatContext *s) {
333 AviSynthContext *avs = s->priv_data;
338 if (avs_has_video(avs->vi)) {
339 st = avformat_new_stream(s, NULL);
341 return AVERROR_UNKNOWN;
343 if (ret = avisynth_create_stream_video(s, st))
346 if (avs_has_audio(avs->vi)) {
347 st = avformat_new_stream(s, NULL);
349 return AVERROR_UNKNOWN;
351 if (ret = avisynth_create_stream_audio(s, st))
357 static int avisynth_open_file(AVFormatContext *s) {
358 AviSynthContext *avs = (AviSynthContext *)s->priv_data;
362 char filename_ansi[MAX_PATH * 4];
363 wchar_t filename_wc[MAX_PATH * 4];
366 if (ret = avisynth_context_create(s))
370 // Convert UTF-8 to ANSI code page
371 MultiByteToWideChar(CP_UTF8, 0, s->filename, -1, filename_wc, MAX_PATH * 4);
372 WideCharToMultiByte(CP_THREAD_ACP, 0, filename_wc, -1, filename_ansi, MAX_PATH * 4, NULL, NULL);
373 arg = avs_new_value_string(filename_ansi);
375 arg = avs_new_value_string(s->filename);
377 val = avs_library->avs_invoke(avs->env, "Import", arg, 0);
378 if (avs_is_error(val)) {
379 av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
380 ret = AVERROR_UNKNOWN;
383 if (!avs_is_clip(val)) {
384 av_log(s, AV_LOG_ERROR, "%s\n", "AviSynth script did not return a clip");
385 ret = AVERROR_UNKNOWN;
389 avs->clip = avs_library->avs_take_clip(val, avs->env);
390 avs->vi = avs_library->avs_get_video_info(avs->clip);
392 // Release the AVS_Value as it will go out of scope.
393 avs_library->avs_release_value(val);
395 if (ret = avisynth_create_stream(s))
401 avisynth_context_destroy(avs);
405 static void avisynth_next_stream(AVFormatContext *s, AVStream **st, AVPacket *pkt, int *discard) {
406 AviSynthContext *avs = s->priv_data;
408 pkt->stream_index = avs->curr_stream++;
409 avs->curr_stream %= s->nb_streams;
411 *st = s->streams[pkt->stream_index];
412 if ((*st)->discard == AVDISCARD_ALL)
420 // Copy AviSynth clip data into an AVPacket.
421 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt, int discard) {
422 AviSynthContext *avs = s->priv_data;
423 AVS_VideoFrame *frame;
424 unsigned char *dst_p;
425 const unsigned char *src_p;
426 int n, i, plane, rowsize, planeheight, pitch, bits;
429 if (avs->curr_frame >= avs->vi->num_frames)
432 // This must happen even if the stream is discarded to prevent desync.
433 n = avs->curr_frame++;
441 // Define the bpp values for the new AviSynth 2.6 colorspaces
442 if (avs_is_yv24(avs->vi)) {
444 } else if (avs_is_yv16(avs->vi)) {
446 } else if (avs_is_yv411(avs->vi)) {
448 } else if (avs_is_y8(avs->vi)) {
451 bits = avs_bits_per_pixel(avs->vi);
454 // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.
455 pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;
457 return AVERROR_UNKNOWN;
458 pkt->data = av_malloc(pkt->size);
460 return AVERROR_UNKNOWN;
462 frame = avs_library->avs_get_frame(avs->clip, n);
463 error = avs_library->avs_clip_get_error(avs->clip);
465 av_log(s, AV_LOG_ERROR, "%s\n", error);
467 av_freep(&pkt->data);
468 return AVERROR_UNKNOWN;
472 for (i = 0; i < avs->n_planes; i++) {
473 plane = avs->planes[i];
474 src_p = avs_get_read_ptr_p(frame, plane);
475 pitch = avs_get_pitch_p(frame, plane);
478 if (avs_library->avs_get_version(avs->clip) == 3) {
479 rowsize = avs_get_row_size_p_25(frame, plane);
480 planeheight = avs_get_height_p_25(frame, plane);
482 rowsize = avs_get_row_size_p(frame, plane);
483 planeheight = avs_get_height_p(frame, plane);
486 rowsize = avs_get_row_size_p(frame, plane);
487 planeheight = avs_get_height_p(frame, plane);
491 if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
492 src_p = src_p + (planeheight - 1) * pitch;
496 avs_library->avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch, rowsize, planeheight);
497 dst_p += rowsize * planeheight;
500 avs_library->avs_release_video_frame(frame);
504 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt, int discard) {
505 AviSynthContext *avs = s->priv_data;
506 AVRational fps, samplerate;
511 if (avs->curr_sample >= avs->vi->num_audio_samples)
514 fps.num = avs->vi->fps_numerator;
515 fps.den = avs->vi->fps_denominator;
516 samplerate.num = avs->vi->audio_samples_per_second;
519 if (avs_has_video(avs->vi)) {
520 if (avs->curr_frame < avs->vi->num_frames)
521 samples = av_rescale_q(avs->curr_frame, samplerate, fps) - avs->curr_sample;
523 samples = av_rescale_q(1, samplerate, fps);
528 // After seeking, audio may catch up with video.
535 if (avs->curr_sample + samples > avs->vi->num_audio_samples)
536 samples = avs->vi->num_audio_samples - avs->curr_sample;
538 // This must happen even if the stream is discarded to prevent desync.
539 n = avs->curr_sample;
540 avs->curr_sample += samples;
546 pkt->duration = samples;
548 pkt->size = avs_bytes_per_channel_sample(avs->vi) * samples * avs->vi->nchannels;
550 return AVERROR_UNKNOWN;
551 pkt->data = av_malloc(pkt->size);
553 return AVERROR_UNKNOWN;
555 avs_library->avs_get_audio(avs->clip, pkt->data, n, samples);
556 error = avs_library->avs_clip_get_error(avs->clip);
558 av_log(s, AV_LOG_ERROR, "%s\n", error);
560 av_freep(&pkt->data);
561 return AVERROR_UNKNOWN;
566 static av_cold int avisynth_read_header(AVFormatContext *s) {
569 // Calling library must implement a lock for thread-safe opens.
570 if (ret = avpriv_lock_avformat())
573 if (ret = avisynth_open_file(s)) {
574 avpriv_unlock_avformat();
578 avpriv_unlock_avformat();
582 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt) {
583 AviSynthContext *avs = s->priv_data;
589 return AVERROR_UNKNOWN;
591 pkt->destruct = av_destruct_packet;
593 // If either stream reaches EOF, try to read the other one before giving up.
594 avisynth_next_stream(s, &st, pkt, &discard);
595 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
596 ret = avisynth_read_packet_video(s, pkt, discard);
597 if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
598 avisynth_next_stream(s, &st, pkt, &discard);
599 return avisynth_read_packet_audio(s, pkt, discard);
603 ret = avisynth_read_packet_audio(s, pkt, discard);
604 if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
605 avisynth_next_stream(s, &st, pkt, &discard);
606 return avisynth_read_packet_video(s, pkt, discard);
612 static av_cold int avisynth_read_close(AVFormatContext *s) {
613 if (avpriv_lock_avformat())
614 return AVERROR_UNKNOWN;
616 avisynth_context_destroy(s->priv_data);
617 avpriv_unlock_avformat();
621 static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
622 AviSynthContext *avs = s->priv_data;
624 AVRational fps, samplerate;
627 return AVERROR_UNKNOWN;
629 fps = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
630 samplerate = (AVRational) {avs->vi->audio_samples_per_second, 1};
632 st = s->streams[stream_index];
633 if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
634 // AviSynth frame counts are signed int.
635 if ((timestamp >= avs->vi->num_frames) || (timestamp > INT_MAX) || (timestamp < 0))
637 avs->curr_frame = timestamp;
638 if (avs_has_audio(avs->vi))
639 avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
641 if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
643 // Force frame granularity for seeking.
644 if (avs_has_video(avs->vi)) {
645 avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
646 avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
648 avs->curr_sample = timestamp;
655 AVInputFormat ff_avisynth_demuxer = {
657 .long_name = NULL_IF_CONFIG_SMALL("AviSynth script"),
658 .priv_data_size = sizeof(AviSynthContext),
659 .read_header = avisynth_read_header,
660 .read_packet = avisynth_read_packet,
661 .read_close = avisynth_read_close,
662 .read_seek = avisynth_read_seek,