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.

408 lines
12KB

  1. /*
  2. * Copyright (c) 2012 Nicolas George
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public License
  8. * 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
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "libavutil/avstring.h"
  21. #include "libavutil/opt.h"
  22. #include "libavutil/parseutils.h"
  23. #include "avformat.h"
  24. #include "internal.h"
  25. typedef struct {
  26. char *url;
  27. int64_t start_time;
  28. int64_t duration;
  29. } ConcatFile;
  30. typedef struct {
  31. AVClass *class;
  32. ConcatFile *files;
  33. ConcatFile *cur_file;
  34. unsigned nb_files;
  35. AVFormatContext *avf;
  36. int safe;
  37. int seekable;
  38. } ConcatContext;
  39. static int concat_probe(AVProbeData *probe)
  40. {
  41. return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
  42. 0 : AVPROBE_SCORE_MAX;
  43. }
  44. static char *get_keyword(uint8_t **cursor)
  45. {
  46. char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
  47. *cursor += strcspn(*cursor, SPACE_CHARS);
  48. if (**cursor) {
  49. *((*cursor)++) = 0;
  50. *cursor += strspn(*cursor, SPACE_CHARS);
  51. }
  52. return ret;
  53. }
  54. static int safe_filename(const char *f)
  55. {
  56. const char *start = f;
  57. for (; *f; f++) {
  58. /* A-Za-z0-9_- */
  59. if (!((unsigned)((*f | 32) - 'a') < 26 ||
  60. (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
  61. if (f == start)
  62. return 0;
  63. else if (*f == '/')
  64. start = f + 1;
  65. else if (*f != '.')
  66. return 0;
  67. }
  68. }
  69. return 1;
  70. }
  71. #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
  72. static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
  73. unsigned *nb_files_alloc)
  74. {
  75. ConcatContext *cat = avf->priv_data;
  76. ConcatFile *file;
  77. char *url = NULL;
  78. size_t url_len;
  79. int ret;
  80. if (cat->safe > 0 && !safe_filename(filename)) {
  81. av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
  82. FAIL(AVERROR(EPERM));
  83. }
  84. url_len = strlen(avf->filename) + strlen(filename) + 16;
  85. if (!(url = av_malloc(url_len)))
  86. FAIL(AVERROR(ENOMEM));
  87. ff_make_absolute_url(url, url_len, avf->filename, filename);
  88. av_freep(&filename);
  89. if (cat->nb_files >= *nb_files_alloc) {
  90. size_t n = FFMAX(*nb_files_alloc * 2, 16);
  91. ConcatFile *new_files;
  92. if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
  93. !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
  94. FAIL(AVERROR(ENOMEM));
  95. cat->files = new_files;
  96. *nb_files_alloc = n;
  97. }
  98. file = &cat->files[cat->nb_files++];
  99. memset(file, 0, sizeof(*file));
  100. *rfile = file;
  101. file->url = url;
  102. file->start_time = AV_NOPTS_VALUE;
  103. file->duration = AV_NOPTS_VALUE;
  104. return 0;
  105. fail:
  106. av_free(url);
  107. av_free(filename);
  108. return ret;
  109. }
  110. static int open_file(AVFormatContext *avf, unsigned fileno)
  111. {
  112. ConcatContext *cat = avf->priv_data;
  113. ConcatFile *file = &cat->files[fileno];
  114. int ret;
  115. if (cat->avf)
  116. avformat_close_input(&cat->avf);
  117. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  118. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  119. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  120. return ret;
  121. }
  122. cat->cur_file = file;
  123. if (file->start_time == AV_NOPTS_VALUE)
  124. file->start_time = !fileno ? 0 :
  125. cat->files[fileno - 1].start_time +
  126. cat->files[fileno - 1].duration;
  127. return 0;
  128. }
  129. static int concat_read_close(AVFormatContext *avf)
  130. {
  131. ConcatContext *cat = avf->priv_data;
  132. unsigned i;
  133. if (cat->avf)
  134. avformat_close_input(&cat->avf);
  135. for (i = 0; i < cat->nb_files; i++)
  136. av_freep(&cat->files[i].url);
  137. av_freep(&cat->files);
  138. return 0;
  139. }
  140. static int concat_read_header(AVFormatContext *avf)
  141. {
  142. ConcatContext *cat = avf->priv_data;
  143. uint8_t buf[4096];
  144. uint8_t *cursor, *keyword;
  145. int ret, line = 0, i;
  146. unsigned nb_files_alloc = 0;
  147. ConcatFile *file = NULL;
  148. AVStream *st, *source_st;
  149. int64_t time = 0;
  150. while (1) {
  151. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  152. break;
  153. line++;
  154. cursor = buf;
  155. keyword = get_keyword(&cursor);
  156. if (!*keyword || *keyword == '#')
  157. continue;
  158. if (!strcmp(keyword, "file")) {
  159. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  160. if (!filename) {
  161. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  162. FAIL(AVERROR_INVALIDDATA);
  163. }
  164. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  165. FAIL(ret);
  166. } else if (!strcmp(keyword, "duration")) {
  167. char *dur_str = get_keyword(&cursor);
  168. int64_t dur;
  169. if (!file) {
  170. av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
  171. line);
  172. FAIL(AVERROR_INVALIDDATA);
  173. }
  174. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  175. av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
  176. line, dur_str);
  177. FAIL(ret);
  178. }
  179. file->duration = dur;
  180. } else if (!strcmp(keyword, "ffconcat")) {
  181. char *ver_kw = get_keyword(&cursor);
  182. char *ver_val = get_keyword(&cursor);
  183. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  184. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  185. FAIL(AVERROR_INVALIDDATA);
  186. }
  187. if (cat->safe < 0)
  188. cat->safe = 1;
  189. } else {
  190. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  191. line, keyword);
  192. FAIL(AVERROR_INVALIDDATA);
  193. }
  194. }
  195. if (ret < 0)
  196. FAIL(ret);
  197. if (!cat->nb_files)
  198. FAIL(AVERROR_INVALIDDATA);
  199. for (i = 0; i < cat->nb_files; i++) {
  200. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  201. cat->files[i].start_time = time;
  202. else
  203. time = cat->files[i].start_time;
  204. if (cat->files[i].duration == AV_NOPTS_VALUE)
  205. break;
  206. time += cat->files[i].duration;
  207. }
  208. if (i == cat->nb_files) {
  209. avf->duration = time;
  210. cat->seekable = 1;
  211. }
  212. if ((ret = open_file(avf, 0)) < 0)
  213. FAIL(ret);
  214. for (i = 0; i < cat->avf->nb_streams; i++) {
  215. if (!(st = avformat_new_stream(avf, NULL)))
  216. FAIL(AVERROR(ENOMEM));
  217. source_st = cat->avf->streams[i];
  218. if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
  219. FAIL(ret);
  220. st->r_frame_rate = source_st->r_frame_rate;
  221. st->avg_frame_rate = source_st->avg_frame_rate;
  222. st->time_base = source_st->time_base;
  223. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  224. }
  225. return 0;
  226. fail:
  227. concat_read_close(avf);
  228. return ret;
  229. }
  230. static int open_next_file(AVFormatContext *avf)
  231. {
  232. ConcatContext *cat = avf->priv_data;
  233. unsigned fileno = cat->cur_file - cat->files;
  234. if (cat->cur_file->duration == AV_NOPTS_VALUE)
  235. cat->cur_file->duration = cat->avf->duration;
  236. if (++fileno >= cat->nb_files)
  237. return AVERROR_EOF;
  238. return open_file(avf, fileno);
  239. }
  240. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  241. {
  242. ConcatContext *cat = avf->priv_data;
  243. int ret;
  244. int64_t delta;
  245. while (1) {
  246. if ((ret = av_read_frame(cat->avf, pkt)) != AVERROR_EOF ||
  247. (ret = open_next_file(avf)) < 0)
  248. break;
  249. }
  250. delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
  251. AV_TIME_BASE_Q,
  252. cat->avf->streams[pkt->stream_index]->time_base);
  253. if (pkt->pts != AV_NOPTS_VALUE)
  254. pkt->pts += delta;
  255. if (pkt->dts != AV_NOPTS_VALUE)
  256. pkt->dts += delta;
  257. return ret;
  258. }
  259. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  260. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  261. {
  262. *ts = av_rescale_q (* ts, tb_in, tb_out);
  263. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  264. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  265. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  266. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  267. }
  268. static int try_seek(AVFormatContext *avf, int stream,
  269. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  270. {
  271. ConcatContext *cat = avf->priv_data;
  272. int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
  273. ts -= t0;
  274. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  275. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  276. if (stream >= 0) {
  277. if (stream >= cat->avf->nb_streams)
  278. return AVERROR(EIO);
  279. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  280. &min_ts, &ts, &max_ts);
  281. }
  282. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  283. }
  284. static int real_seek(AVFormatContext *avf, int stream,
  285. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  286. {
  287. ConcatContext *cat = avf->priv_data;
  288. int ret, left, right;
  289. if (stream >= 0) {
  290. if (stream >= avf->nb_streams)
  291. return AVERROR(EINVAL);
  292. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  293. &min_ts, &ts, &max_ts);
  294. }
  295. left = 0;
  296. right = cat->nb_files;
  297. while (right - left > 1) {
  298. int mid = (left + right) / 2;
  299. if (ts < cat->files[mid].start_time)
  300. right = mid;
  301. else
  302. left = mid;
  303. }
  304. if ((ret = open_file(avf, left)) < 0)
  305. return ret;
  306. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  307. if (ret < 0 &&
  308. left < cat->nb_files - 1 &&
  309. cat->files[left + 1].start_time < max_ts) {
  310. if ((ret = open_file(avf, left + 1)) < 0)
  311. return ret;
  312. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  313. }
  314. return ret;
  315. }
  316. static int concat_seek(AVFormatContext *avf, int stream,
  317. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  318. {
  319. ConcatContext *cat = avf->priv_data;
  320. ConcatFile *cur_file_saved = cat->cur_file;
  321. AVFormatContext *cur_avf_saved = cat->avf;
  322. int ret;
  323. if (!cat->seekable)
  324. return AVERROR(ESPIPE); /* XXX: can we use it? */
  325. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  326. return AVERROR(ENOSYS);
  327. cat->avf = NULL;
  328. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  329. if (cat->avf)
  330. avformat_close_input(&cat->avf);
  331. cat->avf = cur_avf_saved;
  332. cat->cur_file = cur_file_saved;
  333. } else {
  334. avformat_close_input(&cur_avf_saved);
  335. }
  336. return ret;
  337. }
  338. #define OFFSET(x) offsetof(ConcatContext, x)
  339. #define DEC AV_OPT_FLAG_DECODING_PARAM
  340. static const AVOption options[] = {
  341. { "safe", "enable safe mode",
  342. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  343. { NULL }
  344. };
  345. static const AVClass concat_class = {
  346. .class_name = "concat demuxer",
  347. .item_name = av_default_item_name,
  348. .option = options,
  349. .version = LIBAVUTIL_VERSION_INT,
  350. };
  351. AVInputFormat ff_concat_demuxer = {
  352. .name = "concat",
  353. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  354. .priv_data_size = sizeof(ConcatContext),
  355. .read_probe = concat_probe,
  356. .read_header = concat_read_header,
  357. .read_packet = concat_read_packet,
  358. .read_close = concat_read_close,
  359. .read_seek2 = concat_seek,
  360. .priv_class = &concat_class,
  361. };