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.

506 lines
17KB

  1. /*
  2. * Copyright (c) 2010 Stefano Sabatini
  3. * Copyright (c) 2008 Victor Paesa
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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.
  11. *
  12. * FFmpeg 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.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * movie video source
  24. *
  25. * @todo use direct rendering (no allocation of a new frame)
  26. * @todo support a PTS correction mechanism
  27. * @todo support more than one output stream
  28. */
  29. /* #define DEBUG */
  30. #include <float.h>
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/imgutils.h"
  34. #include "libavformat/avformat.h"
  35. #include "audio.h"
  36. #include "avcodec.h"
  37. #include "avfilter.h"
  38. #include "formats.h"
  39. #include "internal.h"
  40. #include "video.h"
  41. typedef enum {
  42. STATE_DECODING,
  43. STATE_FLUSHING,
  44. STATE_DONE,
  45. } MovieState;
  46. typedef struct {
  47. /* common A/V fields */
  48. const AVClass *class;
  49. int64_t seek_point; ///< seekpoint in microseconds
  50. double seek_point_d;
  51. char *format_name;
  52. char *file_name;
  53. int stream_index;
  54. int loop_count;
  55. AVFormatContext *format_ctx;
  56. AVCodecContext *codec_ctx;
  57. MovieState state;
  58. AVFrame *frame; ///< video frame to store the decoded images in
  59. /* video-only fields */
  60. int w, h;
  61. AVFilterBufferRef *picref;
  62. /* audio-only fields */
  63. int bps; ///< bytes per sample
  64. AVPacket pkt, pkt0;
  65. AVFilterBufferRef *samplesref;
  66. } MovieContext;
  67. #define OFFSET(x) offsetof(MovieContext, x)
  68. static const AVOption movie_options[]= {
  69. {"format_name", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX },
  70. {"f", "set format name", OFFSET(format_name), AV_OPT_TYPE_STRING, {.str = 0}, CHAR_MIN, CHAR_MAX },
  71. {"stream_index", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.dbl = -1}, -1, INT_MAX },
  72. {"si", "set stream index", OFFSET(stream_index), AV_OPT_TYPE_INT, {.dbl = -1}, -1, INT_MAX },
  73. {"seek_point", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000 },
  74. {"sp", "set seekpoint (seconds)", OFFSET(seek_point_d), AV_OPT_TYPE_DOUBLE, {.dbl = 0}, 0, (INT64_MAX-1) / 1000000 },
  75. {"loop", "set loop count", OFFSET(loop_count), AV_OPT_TYPE_INT, {.dbl = 1}, 0, INT_MAX },
  76. {NULL},
  77. };
  78. AVFILTER_DEFINE_CLASS(movie);
  79. static av_cold int movie_common_init(AVFilterContext *ctx, const char *args,
  80. enum AVMediaType type)
  81. {
  82. MovieContext *movie = ctx->priv;
  83. AVInputFormat *iformat = NULL;
  84. AVCodec *codec;
  85. int64_t timestamp;
  86. int ret;
  87. movie->class = &movie_class;
  88. av_opt_set_defaults(movie);
  89. if (args)
  90. movie->file_name = av_get_token(&args, ":");
  91. if (!movie->file_name || !*movie->file_name) {
  92. av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
  93. return AVERROR(EINVAL);
  94. }
  95. if (*args++ == ':' && (ret = av_set_options_string(movie, args, "=", ":")) < 0) {
  96. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  97. return ret;
  98. }
  99. movie->seek_point = movie->seek_point_d * 1000000 + 0.5;
  100. av_register_all();
  101. // Try to find the movie format (container)
  102. iformat = movie->format_name ? av_find_input_format(movie->format_name) : NULL;
  103. movie->format_ctx = NULL;
  104. if ((ret = avformat_open_input(&movie->format_ctx, movie->file_name, iformat, NULL)) < 0) {
  105. av_log(ctx, AV_LOG_ERROR,
  106. "Failed to avformat_open_input '%s'\n", movie->file_name);
  107. return ret;
  108. }
  109. if ((ret = avformat_find_stream_info(movie->format_ctx, NULL)) < 0)
  110. av_log(ctx, AV_LOG_WARNING, "Failed to find stream info\n");
  111. // if seeking requested, we execute it
  112. if (movie->seek_point > 0) {
  113. timestamp = movie->seek_point;
  114. // add the stream start time, should it exist
  115. if (movie->format_ctx->start_time != AV_NOPTS_VALUE) {
  116. if (timestamp > INT64_MAX - movie->format_ctx->start_time) {
  117. av_log(ctx, AV_LOG_ERROR,
  118. "%s: seek value overflow with start_time:%"PRId64" seek_point:%"PRId64"\n",
  119. movie->file_name, movie->format_ctx->start_time, movie->seek_point);
  120. return AVERROR(EINVAL);
  121. }
  122. timestamp += movie->format_ctx->start_time;
  123. }
  124. if ((ret = av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD)) < 0) {
  125. av_log(ctx, AV_LOG_ERROR, "%s: could not seek to position %"PRId64"\n",
  126. movie->file_name, timestamp);
  127. return ret;
  128. }
  129. }
  130. /* select the media stream */
  131. if ((ret = av_find_best_stream(movie->format_ctx, type,
  132. movie->stream_index, -1, NULL, 0)) < 0) {
  133. av_log(ctx, AV_LOG_ERROR, "No %s stream with index '%d' found\n",
  134. av_get_media_type_string(type), movie->stream_index);
  135. return ret;
  136. }
  137. movie->stream_index = ret;
  138. movie->codec_ctx = movie->format_ctx->streams[movie->stream_index]->codec;
  139. /*
  140. * So now we've got a pointer to the so-called codec context for our video
  141. * stream, but we still have to find the actual codec and open it.
  142. */
  143. codec = avcodec_find_decoder(movie->codec_ctx->codec_id);
  144. if (!codec) {
  145. av_log(ctx, AV_LOG_ERROR, "Failed to find any codec\n");
  146. return AVERROR(EINVAL);
  147. }
  148. if ((ret = avcodec_open2(movie->codec_ctx, codec, NULL)) < 0) {
  149. av_log(ctx, AV_LOG_ERROR, "Failed to open codec\n");
  150. return ret;
  151. }
  152. av_log(ctx, AV_LOG_VERBOSE, "seek_point:%"PRIi64" format_name:%s file_name:%s stream_index:%d\n",
  153. movie->seek_point, movie->format_name, movie->file_name,
  154. movie->stream_index);
  155. if (!(movie->frame = avcodec_alloc_frame()) ) {
  156. av_log(ctx, AV_LOG_ERROR, "Failed to alloc frame\n");
  157. return AVERROR(ENOMEM);
  158. }
  159. return 0;
  160. }
  161. static av_cold void movie_common_uninit(AVFilterContext *ctx)
  162. {
  163. MovieContext *movie = ctx->priv;
  164. av_free(movie->file_name);
  165. av_free(movie->format_name);
  166. if (movie->codec_ctx)
  167. avcodec_close(movie->codec_ctx);
  168. if (movie->format_ctx)
  169. avformat_close_input(&movie->format_ctx);
  170. avfilter_unref_buffer(movie->picref);
  171. av_freep(&movie->frame);
  172. avfilter_unref_buffer(movie->samplesref);
  173. }
  174. #if CONFIG_MOVIE_FILTER
  175. static av_cold int movie_init(AVFilterContext *ctx, const char *args)
  176. {
  177. MovieContext *movie = ctx->priv;
  178. int ret;
  179. if ((ret = movie_common_init(ctx, args, AVMEDIA_TYPE_VIDEO)) < 0)
  180. return ret;
  181. movie->w = movie->codec_ctx->width;
  182. movie->h = movie->codec_ctx->height;
  183. return 0;
  184. }
  185. static int movie_query_formats(AVFilterContext *ctx)
  186. {
  187. MovieContext *movie = ctx->priv;
  188. enum PixelFormat pix_fmts[] = { movie->codec_ctx->pix_fmt, PIX_FMT_NONE };
  189. ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  190. return 0;
  191. }
  192. static int movie_config_output_props(AVFilterLink *outlink)
  193. {
  194. MovieContext *movie = outlink->src->priv;
  195. outlink->w = movie->w;
  196. outlink->h = movie->h;
  197. outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
  198. return 0;
  199. }
  200. static int movie_get_frame(AVFilterLink *outlink)
  201. {
  202. MovieContext *movie = outlink->src->priv;
  203. AVPacket pkt;
  204. int ret = 0, frame_decoded;
  205. AVStream *st = movie->format_ctx->streams[movie->stream_index];
  206. if (movie->state == STATE_DONE)
  207. return 0;
  208. while (1) {
  209. if (movie->state == STATE_DECODING) {
  210. ret = av_read_frame(movie->format_ctx, &pkt);
  211. if (ret == AVERROR_EOF) {
  212. int64_t timestamp;
  213. if (movie->loop_count != 1) {
  214. timestamp = movie->seek_point;
  215. if (movie->format_ctx->start_time != AV_NOPTS_VALUE)
  216. timestamp += movie->format_ctx->start_time;
  217. if (av_seek_frame(movie->format_ctx, -1, timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
  218. movie->state = STATE_FLUSHING;
  219. } else if (movie->loop_count>1)
  220. movie->loop_count--;
  221. continue;
  222. } else {
  223. movie->state = STATE_FLUSHING;
  224. }
  225. } else if (ret < 0)
  226. break;
  227. }
  228. // Is this a packet from the video stream?
  229. if (pkt.stream_index == movie->stream_index || movie->state == STATE_FLUSHING) {
  230. avcodec_decode_video2(movie->codec_ctx, movie->frame, &frame_decoded, &pkt);
  231. if (frame_decoded) {
  232. /* FIXME: avoid the memcpy */
  233. movie->picref = ff_get_video_buffer(outlink, AV_PERM_WRITE | AV_PERM_PRESERVE |
  234. AV_PERM_REUSE2, outlink->w, outlink->h);
  235. av_image_copy(movie->picref->data, movie->picref->linesize,
  236. (void*)movie->frame->data, movie->frame->linesize,
  237. movie->picref->format, outlink->w, outlink->h);
  238. avfilter_copy_frame_props(movie->picref, movie->frame);
  239. /* FIXME: use a PTS correction mechanism as that in
  240. * ffplay.c when some API will be available for that */
  241. /* use pkt_dts if pkt_pts is not available */
  242. movie->picref->pts = movie->frame->pkt_pts == AV_NOPTS_VALUE ?
  243. movie->frame->pkt_dts : movie->frame->pkt_pts;
  244. if (!movie->frame->sample_aspect_ratio.num)
  245. movie->picref->video->sample_aspect_ratio = st->sample_aspect_ratio;
  246. av_dlog(outlink->src,
  247. "movie_get_frame(): file:'%s' pts:%"PRId64" time:%lf pos:%"PRId64" aspect:%d/%d\n",
  248. movie->file_name, movie->picref->pts,
  249. (double)movie->picref->pts * av_q2d(st->time_base),
  250. movie->picref->pos,
  251. movie->picref->video->sample_aspect_ratio.num,
  252. movie->picref->video->sample_aspect_ratio.den);
  253. // We got it. Free the packet since we are returning
  254. av_free_packet(&pkt);
  255. return 0;
  256. } else if (movie->state == STATE_FLUSHING) {
  257. movie->state = STATE_DONE;
  258. av_free_packet(&pkt);
  259. return AVERROR_EOF;
  260. }
  261. }
  262. // Free the packet that was allocated by av_read_frame
  263. av_free_packet(&pkt);
  264. }
  265. return ret;
  266. }
  267. static int movie_request_frame(AVFilterLink *outlink)
  268. {
  269. AVFilterBufferRef *outpicref;
  270. MovieContext *movie = outlink->src->priv;
  271. int ret;
  272. if (movie->state == STATE_DONE)
  273. return AVERROR_EOF;
  274. if ((ret = movie_get_frame(outlink)) < 0)
  275. return ret;
  276. outpicref = avfilter_ref_buffer(movie->picref, ~0);
  277. if (!outpicref) {
  278. ret = AVERROR(ENOMEM);
  279. goto fail;
  280. }
  281. ret = ff_start_frame(outlink, outpicref);
  282. if (ret < 0)
  283. goto fail;
  284. ret = ff_draw_slice(outlink, 0, outlink->h, 1);
  285. if (ret < 0)
  286. goto fail;
  287. ret = ff_end_frame(outlink);
  288. fail:
  289. avfilter_unref_bufferp(&movie->picref);
  290. return ret;
  291. }
  292. AVFilter avfilter_vsrc_movie = {
  293. .name = "movie",
  294. .description = NULL_IF_CONFIG_SMALL("Read from a movie source."),
  295. .priv_size = sizeof(MovieContext),
  296. .init = movie_init,
  297. .uninit = movie_common_uninit,
  298. .query_formats = movie_query_formats,
  299. .inputs = (const AVFilterPad[]) {{ .name = NULL }},
  300. .outputs = (const AVFilterPad[]) {{ .name = "default",
  301. .type = AVMEDIA_TYPE_VIDEO,
  302. .request_frame = movie_request_frame,
  303. .config_props = movie_config_output_props, },
  304. { .name = NULL}},
  305. };
  306. #endif /* CONFIG_MOVIE_FILTER */
  307. #if CONFIG_AMOVIE_FILTER
  308. static av_cold int amovie_init(AVFilterContext *ctx, const char *args)
  309. {
  310. MovieContext *movie = ctx->priv;
  311. int ret;
  312. if ((ret = movie_common_init(ctx, args, AVMEDIA_TYPE_AUDIO)) < 0)
  313. return ret;
  314. movie->bps = av_get_bytes_per_sample(movie->codec_ctx->sample_fmt);
  315. return 0;
  316. }
  317. static int amovie_query_formats(AVFilterContext *ctx)
  318. {
  319. MovieContext *movie = ctx->priv;
  320. AVCodecContext *c = movie->codec_ctx;
  321. enum AVSampleFormat sample_fmts[] = { c->sample_fmt, -1 };
  322. int sample_rates[] = { c->sample_rate, -1 };
  323. int64_t chlayouts[] = { c->channel_layout ? c->channel_layout :
  324. av_get_default_channel_layout(c->channels), -1 };
  325. ff_set_common_formats (ctx, ff_make_format_list(sample_fmts));
  326. ff_set_common_samplerates (ctx, ff_make_format_list(sample_rates));
  327. ff_set_common_channel_layouts(ctx, avfilter_make_format64_list(chlayouts));
  328. return 0;
  329. }
  330. static int amovie_config_output_props(AVFilterLink *outlink)
  331. {
  332. MovieContext *movie = outlink->src->priv;
  333. AVCodecContext *c = movie->codec_ctx;
  334. outlink->sample_rate = c->sample_rate;
  335. outlink->time_base = movie->format_ctx->streams[movie->stream_index]->time_base;
  336. return 0;
  337. }
  338. static int amovie_get_samples(AVFilterLink *outlink)
  339. {
  340. MovieContext *movie = outlink->src->priv;
  341. AVPacket pkt;
  342. int ret, got_frame = 0;
  343. if (!movie->pkt.size && movie->state == STATE_DONE)
  344. return AVERROR_EOF;
  345. /* check for another frame, in case the previous one was completely consumed */
  346. if (!movie->pkt.size) {
  347. while ((ret = av_read_frame(movie->format_ctx, &pkt)) >= 0) {
  348. // Is this a packet from the selected stream?
  349. if (pkt.stream_index != movie->stream_index) {
  350. av_free_packet(&pkt);
  351. continue;
  352. } else {
  353. movie->pkt0 = movie->pkt = pkt;
  354. break;
  355. }
  356. }
  357. if (ret == AVERROR_EOF) {
  358. movie->state = STATE_DONE;
  359. return ret;
  360. }
  361. }
  362. /* decode and update the movie pkt */
  363. avcodec_get_frame_defaults(movie->frame);
  364. ret = avcodec_decode_audio4(movie->codec_ctx, movie->frame, &got_frame, &movie->pkt);
  365. if (ret < 0) {
  366. movie->pkt.size = 0;
  367. return ret;
  368. }
  369. movie->pkt.data += ret;
  370. movie->pkt.size -= ret;
  371. /* wrap the decoded data in a samplesref */
  372. if (got_frame) {
  373. int nb_samples = movie->frame->nb_samples;
  374. int data_size =
  375. av_samples_get_buffer_size(NULL, movie->codec_ctx->channels,
  376. nb_samples, movie->codec_ctx->sample_fmt, 1);
  377. if (data_size < 0)
  378. return data_size;
  379. movie->samplesref =
  380. ff_get_audio_buffer(outlink, AV_PERM_WRITE, nb_samples);
  381. memcpy(movie->samplesref->data[0], movie->frame->data[0], data_size);
  382. movie->samplesref->pts = movie->pkt.pts;
  383. movie->samplesref->pos = movie->pkt.pos;
  384. movie->samplesref->audio->sample_rate = movie->codec_ctx->sample_rate;
  385. }
  386. // We got it. Free the packet since we are returning
  387. if (movie->pkt.size <= 0)
  388. av_free_packet(&movie->pkt0);
  389. return 0;
  390. }
  391. static int amovie_request_frame(AVFilterLink *outlink)
  392. {
  393. MovieContext *movie = outlink->src->priv;
  394. int ret;
  395. if (movie->state == STATE_DONE)
  396. return AVERROR_EOF;
  397. do {
  398. if ((ret = amovie_get_samples(outlink)) < 0)
  399. return ret;
  400. } while (!movie->samplesref);
  401. ff_filter_samples(outlink, avfilter_ref_buffer(movie->samplesref, ~0));
  402. avfilter_unref_buffer(movie->samplesref);
  403. movie->samplesref = NULL;
  404. return 0;
  405. }
  406. AVFilter avfilter_asrc_amovie = {
  407. .name = "amovie",
  408. .description = NULL_IF_CONFIG_SMALL("Read audio from a movie source."),
  409. .priv_size = sizeof(MovieContext),
  410. .init = amovie_init,
  411. .uninit = movie_common_uninit,
  412. .query_formats = amovie_query_formats,
  413. .inputs = (const AVFilterPad[]) {{ .name = NULL }},
  414. .outputs = (const AVFilterPad[]) {{ .name = "default",
  415. .type = AVMEDIA_TYPE_AUDIO,
  416. .request_frame = amovie_request_frame,
  417. .config_props = amovie_config_output_props, },
  418. { .name = NULL}},
  419. };
  420. #endif /* CONFIG_AMOVIE_FILTER */