You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

640 lines
18KB

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