]> git.sesse.net Git - ffmpeg/blob - libavformat/avisynth.c
lavfi/overlay: simpler up-rounded w/h computations.
[ffmpeg] / libavformat / avisynth.c
1 /*
2  * Avi/AvxSynth support
3  * Copyright (c) 2012 AvxSynth Team.
4  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "avformat.h"
22 #include "internal.h"
23 #include "libavcodec/internal.h"
24
25 // Enable function pointer definitions for runtime loading.
26 #define AVSC_NO_DECLSPEC
27
28 // Shut up ffmpeg error messages.
29 // avisynth_c.h contains inline functions that call these functions.
30 #undef malloc
31 #undef free
32 #undef printf
33
34 // Platform-specific directives for AviSynth vs AvxSynth.
35 #ifdef _WIN32
36   #include <windows.h>
37   #undef EXTERN_C
38   #include "compat/avisynth/avisynth_c.h"
39   #define AVISYNTH_LIB "avisynth"
40 #else
41   #include <dlfcn.h>
42   #include "compat/avisynth/avxsynth_c.h"
43    #if defined (__APPLE__)
44      #define AVISYNTH_LIB "libavxsynth.dylib"
45    #else
46      #define AVISYNTH_LIB "libavxsynth.so"
47    #endif
48
49   #define LoadLibrary(x) dlopen(x, RTLD_NOW | RTLD_GLOBAL)
50   #define GetProcAddress dlsym
51   #define FreeLibrary dlclose
52 #endif
53
54 // AvxSynth doesn't have these colorspaces, so disable them
55 #ifndef _WIN32
56 #define avs_is_yv24(vi) 0
57 #define avs_is_yv16(vi) 0
58 #define avs_is_yv411(vi) 0
59 #define avs_is_y8(vi) 0
60 #endif
61
62 typedef struct {
63     void *library;
64 #define AVSC_DECLARE_FUNC(name) name##_func name
65     AVSC_DECLARE_FUNC(avs_create_script_environment);
66     AVSC_DECLARE_FUNC(avs_delete_script_environment);
67     AVSC_DECLARE_FUNC(avs_get_error);
68     AVSC_DECLARE_FUNC(avs_clip_get_error);
69     AVSC_DECLARE_FUNC(avs_invoke);
70     AVSC_DECLARE_FUNC(avs_release_value);
71     AVSC_DECLARE_FUNC(avs_get_video_info);
72     AVSC_DECLARE_FUNC(avs_take_clip);
73     AVSC_DECLARE_FUNC(avs_release_clip);
74     AVSC_DECLARE_FUNC(avs_bit_blt);
75     AVSC_DECLARE_FUNC(avs_get_audio);
76     AVSC_DECLARE_FUNC(avs_get_frame);
77     AVSC_DECLARE_FUNC(avs_release_video_frame);
78 #undef AVSC_DECLARE_FUNC
79 } AviSynthLibrary;
80
81 struct AviSynthContext {
82     AVS_ScriptEnvironment *env;
83     AVS_Clip *clip;
84     const AVS_VideoInfo *vi;
85
86     // avisynth_read_packet_video() iterates over this.
87     int n_planes;
88     const int *planes;
89
90     int curr_stream;
91     int curr_frame;
92     int64_t curr_sample;
93
94     int error;
95
96     // Linked list pointers.
97     struct AviSynthContext *next;
98 };
99 typedef struct AviSynthContext AviSynthContext;
100
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, AVS_PLANAR_V};
104
105 // A conflict between C++ global objects, atexit, and dynamic loading requires
106 // us to register our own atexit handler to prevent double freeing.
107 static AviSynthLibrary *avs_library = NULL;
108 static int avs_atexit_called = 0;
109
110 // Linked list of AviSynthContexts. An atexit handler destroys this list.
111 static AviSynthContext *avs_ctx_list = NULL;
112
113 static av_cold void avisynth_atexit_handler(void);
114
115 static av_cold int avisynth_load_library(void) {
116     avs_library = av_mallocz(sizeof(AviSynthLibrary));
117     if (!avs_library)
118         return AVERROR_UNKNOWN;
119
120     avs_library->library = LoadLibrary(AVISYNTH_LIB);
121     if (!avs_library->library)
122         goto init_fail;
123
124 #define LOAD_AVS_FUNC(name, continue_on_fail) \
125 { \
126     avs_library->name = (void*)GetProcAddress(avs_library->library, #name); \
127     if(!continue_on_fail && !avs_library->name) \
128         goto fail; \
129 }
130     LOAD_AVS_FUNC(avs_create_script_environment, 0);
131     LOAD_AVS_FUNC(avs_delete_script_environment, 0);
132     LOAD_AVS_FUNC(avs_get_error, 1); // New to AviSynth 2.6
133     LOAD_AVS_FUNC(avs_clip_get_error, 0);
134     LOAD_AVS_FUNC(avs_invoke, 0);
135     LOAD_AVS_FUNC(avs_release_value, 0);
136     LOAD_AVS_FUNC(avs_get_video_info, 0);
137     LOAD_AVS_FUNC(avs_take_clip, 0);
138     LOAD_AVS_FUNC(avs_release_clip, 0);
139     LOAD_AVS_FUNC(avs_bit_blt, 0);
140     LOAD_AVS_FUNC(avs_get_audio, 0);
141     LOAD_AVS_FUNC(avs_get_frame, 0);
142     LOAD_AVS_FUNC(avs_release_video_frame, 0);
143 #undef LOAD_AVS_FUNC
144
145     atexit(avisynth_atexit_handler);
146     return 0;
147
148 fail:
149     FreeLibrary(avs_library->library);
150 init_fail:
151     av_freep(&avs_library);
152     return AVERROR_UNKNOWN;
153 }
154
155 // Note that avisynth_context_create and avisynth_context_destroy
156 // do not allocate or free the actual context! That is taken care of
157 // by libavformat.
158 static av_cold int avisynth_context_create(AVFormatContext *s) {
159     AviSynthContext *avs = (AviSynthContext *)s->priv_data;
160     int ret;
161
162     if (!avs_library) {
163         if (ret = avisynth_load_library())
164             return ret;
165     }
166
167     avs->env = avs_library->avs_create_script_environment(3);
168     if (avs_library->avs_get_error) {
169         const char *error = avs_library->avs_get_error(avs->env);
170         if (error) {
171             av_log(s, AV_LOG_ERROR, "%s\n", error);
172             return AVERROR_UNKNOWN;
173         }
174     }
175
176     if (!avs_ctx_list) {
177         avs_ctx_list = avs;
178     } else {
179         avs->next = avs_ctx_list;
180         avs_ctx_list = avs;
181     }
182
183     return 0;
184 }
185
186 static av_cold void avisynth_context_destroy(AviSynthContext *avs) {
187     if (avs_atexit_called)
188        return;
189
190     if (avs == avs_ctx_list) {
191         avs_ctx_list = avs->next;
192     } else {
193         AviSynthContext *prev = avs_ctx_list;
194         while (prev->next != avs)
195             prev = prev->next;
196         prev->next = avs->next;
197     }
198
199     if (avs->clip) {
200         avs_library->avs_release_clip(avs->clip);
201         avs->clip = NULL;
202     }
203     if (avs->env) {
204         avs_library->avs_delete_script_environment(avs->env);
205         avs->env = NULL;
206     }
207 }
208
209 static av_cold void avisynth_atexit_handler(void) {
210     AviSynthContext *avs = avs_ctx_list;
211
212     while (avs) {
213         AviSynthContext *next = avs->next;
214         avisynth_context_destroy(avs);
215         avs = next;
216     }
217     FreeLibrary(avs_library->library);
218     av_freep(&avs_library);
219
220     avs_atexit_called = 1;
221 }
222
223 // Create AVStream from audio and video data.
224 static int avisynth_create_stream_video(AVFormatContext *s, AVStream *st) {
225     AviSynthContext *avs = s->priv_data;
226     int planar = 0; // 0: packed, 1: YUV, 2: Y8
227
228     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
229     st->codec->codec_id = CODEC_ID_RAWVIDEO;
230     st->codec->width = avs->vi->width;
231     st->codec->height = avs->vi->height;
232
233     st->time_base = (AVRational) {avs->vi->fps_denominator, avs->vi->fps_numerator};
234     st->avg_frame_rate = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
235     st->start_time = 0;
236     st->duration = avs->vi->num_frames;
237     st->nb_frames = avs->vi->num_frames;
238
239     switch (avs->vi->pixel_type) {
240 #ifdef _WIN32
241     case AVS_CS_YV24:
242         st->codec->pix_fmt = PIX_FMT_YUV444P;
243         planar = 1;
244         break;
245     case AVS_CS_YV16:
246         st->codec->pix_fmt = PIX_FMT_YUV422P;
247         planar = 1;
248         break;
249     case AVS_CS_YV411:
250         st->codec->pix_fmt = PIX_FMT_YUV411P;
251         planar = 1;
252         break;
253     case AVS_CS_Y8:
254         st->codec->pix_fmt = PIX_FMT_GRAY8;
255         planar = 2;
256         break;
257 #endif
258     case AVS_CS_BGR24:
259         st->codec->pix_fmt = PIX_FMT_BGR24;
260         break;
261     case AVS_CS_BGR32:
262         st->codec->pix_fmt = PIX_FMT_RGB32;
263         break;
264     case AVS_CS_YUY2:
265         st->codec->pix_fmt = PIX_FMT_YUYV422;
266         break;
267     case AVS_CS_YV12:
268         st->codec->pix_fmt = PIX_FMT_YUV420P;
269         planar = 1;
270         break;
271     case AVS_CS_I420: // Is this even used anywhere?
272         st->codec->pix_fmt = PIX_FMT_YUV420P;
273         planar = 1;
274         break;
275     default:
276         av_log(s, AV_LOG_ERROR, "unknown AviSynth colorspace %d\n", avs->vi->pixel_type);
277         avs->error = 1;
278         return AVERROR_UNKNOWN;
279     }
280
281     switch (planar) {
282     case 2: // Y8
283         avs->n_planes = 1;
284         avs->planes = avs_planes_grey;
285         break;
286     case 1: // YUV
287         avs->n_planes = 3;
288         avs->planes = avs_planes_yuv;
289         break;
290     default:
291         avs->n_planes = 1;
292         avs->planes = avs_planes_packed;
293     }
294     return 0;
295 }
296
297 static int avisynth_create_stream_audio(AVFormatContext *s, AVStream *st) {
298     AviSynthContext *avs = s->priv_data;
299
300     st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
301     st->codec->sample_rate = avs->vi->audio_samples_per_second;
302     st->codec->channels = avs->vi->nchannels;
303     st->time_base = (AVRational) {1, avs->vi->audio_samples_per_second};
304
305     switch (avs->vi->sample_type) {
306     case AVS_SAMPLE_INT8:
307         st->codec->codec_id = CODEC_ID_PCM_U8;
308         break;
309     case AVS_SAMPLE_INT16:
310         st->codec->codec_id = CODEC_ID_PCM_S16LE;
311         break;
312     case AVS_SAMPLE_INT24:
313         st->codec->codec_id = CODEC_ID_PCM_S24LE;
314         break;
315     case AVS_SAMPLE_INT32:
316         st->codec->codec_id = CODEC_ID_PCM_S32LE;
317         break;
318     case AVS_SAMPLE_FLOAT:
319         st->codec->codec_id = CODEC_ID_PCM_F32LE;
320         break;
321     default:
322         av_log(s, AV_LOG_ERROR, "unknown AviSynth sample type %d\n", avs->vi->sample_type);
323         avs->error = 1;
324         return AVERROR_UNKNOWN;
325     }
326     return 0;
327 }
328
329 static int avisynth_create_stream(AVFormatContext *s) {
330     AviSynthContext *avs = s->priv_data;
331     AVStream *st;
332     int ret;
333     int id = 0;
334
335     if (avs_has_video(avs->vi)) {
336         st = avformat_new_stream(s, NULL);
337         if (!st)
338             return AVERROR_UNKNOWN;
339         st->id = id++;
340         if (ret = avisynth_create_stream_video(s, st))
341             return ret;
342     }
343     if (avs_has_audio(avs->vi)) {
344         st = avformat_new_stream(s, NULL);
345         if (!st)
346             return AVERROR_UNKNOWN;
347         st->id = id++;
348         if (ret = avisynth_create_stream_audio(s, st))
349             return ret;
350     }
351     return 0;
352 }
353
354 static int avisynth_open_file(AVFormatContext *s) {
355     AviSynthContext *avs = (AviSynthContext *)s->priv_data;
356     AVS_Value arg, val;
357     int ret;
358
359     if (ret = avisynth_context_create(s))
360         return ret;
361
362     arg = avs_new_value_string(s->filename);
363     val = avs_library->avs_invoke(avs->env, "Import", arg, 0);
364     if (avs_is_error(val)) {
365         av_log(s, AV_LOG_ERROR, "%s\n", avs_as_error(val));
366         ret = AVERROR_UNKNOWN;
367         goto fail;
368     }
369     if (!avs_is_clip(val)) {
370         av_log(s, AV_LOG_ERROR, "%s\n", "AviSynth script did not return a clip");
371         ret = AVERROR_UNKNOWN;
372         goto fail;
373     }
374
375     avs->clip = avs_library->avs_take_clip(val, avs->env);
376     avs->vi = avs_library->avs_get_video_info(avs->clip);
377
378     // Release the AVS_Value as it will go out of scope.
379     avs_library->avs_release_value(val);
380
381     if (ret = avisynth_create_stream(s))
382         goto fail;
383
384     return 0;
385
386 fail:
387     avisynth_context_destroy(avs);
388     return ret;
389 }
390
391 static void avisynth_next_stream(AVFormatContext *s, AVStream **st, AVPacket *pkt, int *discard) {
392     AviSynthContext *avs = s->priv_data;
393
394     pkt->stream_index = avs->curr_stream++;
395     avs->curr_stream %= s->nb_streams;
396
397     *st = s->streams[pkt->stream_index];
398     if ((*st)->discard == AVDISCARD_ALL)
399         *discard = 1;
400     else
401         *discard = 0;
402
403     return;
404 }
405
406 // Copy AviSynth clip data into an AVPacket.
407 static int avisynth_read_packet_video(AVFormatContext *s, AVPacket *pkt, int discard) {
408     AviSynthContext *avs = s->priv_data;
409     AVS_VideoFrame *frame;
410     unsigned char *dst_p;
411     const unsigned char *src_p;
412     int n, i, plane, rowsize, planeheight, pitch, bits;
413     const char *error;
414
415     if (avs->curr_frame >= avs->vi->num_frames)
416         return AVERROR_EOF;
417
418     // This must happen even if the stream is discarded to prevent desync.
419     n = avs->curr_frame++;
420     if (discard)
421         return 0;
422
423     pkt->pts = n;
424     pkt->dts = n;
425     pkt->duration = 1;
426
427     // Define the bpp values for the new AviSynth 2.6 colorspaces
428     if (avs_is_yv24(avs->vi)) {
429         bits = 24;
430     } else if (avs_is_yv16(avs->vi)) {
431         bits = 16;
432     } else if (avs_is_yv411(avs->vi)) {
433         bits = 12;
434     } else if (avs_is_y8(avs->vi)) {
435         bits = 8;
436     } else {
437         bits = avs_bits_per_pixel(avs->vi);
438     }
439
440     // Without cast to int64_t, calculation overflows at about 9k x 9k resolution.
441     pkt->size = (((int64_t)avs->vi->width * (int64_t)avs->vi->height) * bits) / 8;
442     if (!pkt->size)
443         return AVERROR_UNKNOWN;
444     pkt->data = av_malloc(pkt->size);
445     if (!pkt->data)
446         return AVERROR_UNKNOWN;
447
448     frame = avs_library->avs_get_frame(avs->clip, n);
449     error = avs_library->avs_clip_get_error(avs->clip);
450     if (error) {
451         av_log(s, AV_LOG_ERROR, "%s\n", error);
452         avs->error = 1;
453         av_freep(&pkt->data);
454         return AVERROR_UNKNOWN;
455     }
456
457     dst_p = pkt->data;
458     for (i = 0; i < avs->n_planes; i++) {
459         plane = avs->planes[i];
460         src_p = avs_get_read_ptr_p(frame, plane);
461         rowsize = avs_get_row_size_p(frame, plane);
462         planeheight = avs_get_height_p(frame, plane);
463         pitch = avs_get_pitch_p(frame, plane);
464
465         // Flip RGB video.
466         if (avs_is_rgb24(avs->vi) || avs_is_rgb(avs->vi)) {
467             src_p = src_p + (planeheight - 1) * pitch;
468             pitch = -pitch;
469         }
470
471         avs_library->avs_bit_blt(avs->env, dst_p, rowsize, src_p, pitch, rowsize, planeheight);
472         dst_p += rowsize * planeheight;
473     }
474
475     avs_library->avs_release_video_frame(frame);
476     return 0;
477 }
478
479 static int avisynth_read_packet_audio(AVFormatContext *s, AVPacket *pkt, int discard) {
480     AviSynthContext *avs = s->priv_data;
481     AVRational fps, samplerate;
482     int samples;
483     int64_t n;
484     const char *error;
485
486     if (avs->curr_sample >= avs->vi->num_audio_samples)
487         return AVERROR_EOF;
488
489     fps.num = avs->vi->fps_numerator;
490     fps.den = avs->vi->fps_denominator;
491     samplerate.num = avs->vi->audio_samples_per_second;
492     samplerate.den = 1;
493
494     if (avs_has_video(avs->vi)) {
495         if (avs->curr_frame < avs->vi->num_frames)
496             samples = av_rescale_q(avs->curr_frame, samplerate, fps) - avs->curr_sample;
497         else
498             samples = av_rescale_q(1, samplerate, fps);
499     } else {
500         samples = 1000;
501     }
502
503     // After seeking, audio may catch up with video.
504     if (samples <= 0) {
505         pkt->size = 0;
506         pkt->data = NULL;
507         return 0;
508     }
509
510     if (avs->curr_sample + samples > avs->vi->num_audio_samples)
511         samples = avs->vi->num_audio_samples - avs->curr_sample;
512
513     // This must happen even if the stream is discarded to prevent desync.
514     n = avs->curr_sample;
515     avs->curr_sample += samples;
516     if (discard)
517         return 0;
518
519     pkt->pts = n;
520     pkt->dts = n;
521     pkt->duration = samples;
522
523     pkt->size = avs_bytes_per_channel_sample(avs->vi) * samples * avs->vi->nchannels;
524     if (!pkt->size)
525         return AVERROR_UNKNOWN;
526     pkt->data = av_malloc(pkt->size);
527     if (!pkt->data)
528         return AVERROR_UNKNOWN;
529
530     avs_library->avs_get_audio(avs->clip, pkt->data, n, samples);
531     error = avs_library->avs_clip_get_error(avs->clip);
532     if (error) {
533         av_log(s, AV_LOG_ERROR, "%s\n", error);
534         avs->error = 1;
535         av_freep(&pkt->data);
536         return AVERROR_UNKNOWN;
537     }
538     return 0;
539 }
540
541 static av_cold int avisynth_read_header(AVFormatContext *s) {
542     int ret;
543
544     // Calling library must implement a lock for thread-safe opens.
545     if (ret = avpriv_lock_avformat())
546         return ret;
547
548     if (ret = avisynth_open_file(s)) {
549         avpriv_unlock_avformat();
550         return ret;
551     }
552
553     avpriv_unlock_avformat();
554     return 0;
555 }
556
557 static int avisynth_read_packet(AVFormatContext *s, AVPacket *pkt) {
558     AviSynthContext *avs = s->priv_data;
559     AVStream *st;
560     int discard = 0;
561     int ret;
562
563     if (avs->error)
564         return AVERROR_UNKNOWN;
565
566     pkt->destruct = av_destruct_packet;
567
568     // If either stream reaches EOF, try to read the other one before giving up.
569     avisynth_next_stream(s, &st, pkt, &discard);
570     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
571         ret = avisynth_read_packet_video(s, pkt, discard);
572         if (ret == AVERROR_EOF && avs_has_audio(avs->vi)) {
573             avisynth_next_stream(s, &st, pkt, &discard);
574             return avisynth_read_packet_audio(s, pkt, discard);
575         }
576         return ret;
577     } else {
578         ret = avisynth_read_packet_audio(s, pkt, discard);
579         if (ret == AVERROR_EOF && avs_has_video(avs->vi)) {
580             avisynth_next_stream(s, &st, pkt, &discard);
581             return avisynth_read_packet_video(s, pkt, discard);
582         }
583         return ret;
584     }
585 }
586
587 static av_cold int avisynth_read_close(AVFormatContext *s) {
588     if (avpriv_lock_avformat())
589         return AVERROR_UNKNOWN;
590
591     avisynth_context_destroy(s->priv_data);
592     avpriv_unlock_avformat();
593     return 0;
594 }
595
596 static int avisynth_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
597     AviSynthContext *avs = s->priv_data;
598     AVStream *st;
599     AVRational fps, samplerate;
600
601     if (avs->error)
602         return AVERROR_UNKNOWN;
603
604     fps = (AVRational) {avs->vi->fps_numerator, avs->vi->fps_denominator};
605     samplerate = (AVRational) {avs->vi->audio_samples_per_second, 1};
606
607     st = s->streams[stream_index];
608     if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
609         // AviSynth frame counts are signed int.
610         if ((timestamp >= avs->vi->num_frames) || (timestamp > INT_MAX) || (timestamp < 0))
611             return AVERROR_EOF;
612         avs->curr_frame = timestamp;
613         if (avs_has_audio(avs->vi))
614             avs->curr_sample = av_rescale_q(timestamp, samplerate, fps);
615     } else {
616         if ((timestamp >= avs->vi->num_audio_samples) || (timestamp < 0))
617             return AVERROR_EOF;
618         // Force frame granularity for seeking.
619         if (avs_has_video(avs->vi)) {
620             avs->curr_frame = av_rescale_q(timestamp, fps, samplerate);
621             avs->curr_sample = av_rescale_q(avs->curr_frame, samplerate, fps);
622         } else {
623             avs->curr_sample = timestamp;
624         }
625     }
626
627     return 0;
628 }
629
630 AVInputFormat ff_avisynth_demuxer = {
631     .name           = "avisynth",
632     .long_name      = NULL_IF_CONFIG_SMALL("AviSynth script"),
633     .priv_data_size = sizeof(AviSynthContext),
634     .read_header    = avisynth_read_header,
635     .read_packet    = avisynth_read_packet,
636     .read_close     = avisynth_read_close,
637     .read_seek      = avisynth_read_seek,
638     .extensions     = "avs",
639 };