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.

549 lines
16KB

  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. #include "url.h"
  26. typedef enum ConcatMatchMode {
  27. MATCH_ONE_TO_ONE,
  28. MATCH_EXACT_ID,
  29. } ConcatMatchMode;
  30. typedef struct ConcatStream {
  31. int out_stream_index;
  32. } ConcatStream;
  33. typedef struct {
  34. char *url;
  35. int64_t start_time;
  36. int64_t duration;
  37. ConcatStream *streams;
  38. int nb_streams;
  39. } ConcatFile;
  40. typedef struct {
  41. AVClass *class;
  42. ConcatFile *files;
  43. ConcatFile *cur_file;
  44. unsigned nb_files;
  45. AVFormatContext *avf;
  46. int safe;
  47. int seekable;
  48. ConcatMatchMode stream_match_mode;
  49. } ConcatContext;
  50. static int concat_probe(AVProbeData *probe)
  51. {
  52. return memcmp(probe->buf, "ffconcat version 1.0", 20) ?
  53. 0 : AVPROBE_SCORE_MAX;
  54. }
  55. static char *get_keyword(uint8_t **cursor)
  56. {
  57. char *ret = *cursor += strspn(*cursor, SPACE_CHARS);
  58. *cursor += strcspn(*cursor, SPACE_CHARS);
  59. if (**cursor) {
  60. *((*cursor)++) = 0;
  61. *cursor += strspn(*cursor, SPACE_CHARS);
  62. }
  63. return ret;
  64. }
  65. static int safe_filename(const char *f)
  66. {
  67. const char *start = f;
  68. for (; *f; f++) {
  69. /* A-Za-z0-9_- */
  70. if (!((unsigned)((*f | 32) - 'a') < 26 ||
  71. (unsigned)(*f - '0') < 10 || *f == '_' || *f == '-')) {
  72. if (f == start)
  73. return 0;
  74. else if (*f == '/')
  75. start = f + 1;
  76. else if (*f != '.')
  77. return 0;
  78. }
  79. }
  80. return 1;
  81. }
  82. #define FAIL(retcode) do { ret = (retcode); goto fail; } while(0)
  83. static int add_file(AVFormatContext *avf, char *filename, ConcatFile **rfile,
  84. unsigned *nb_files_alloc)
  85. {
  86. ConcatContext *cat = avf->priv_data;
  87. ConcatFile *file;
  88. char *url = NULL;
  89. const char *proto;
  90. size_t url_len, proto_len;
  91. int ret;
  92. if (cat->safe > 0 && !safe_filename(filename)) {
  93. av_log(avf, AV_LOG_ERROR, "Unsafe file name '%s'\n", filename);
  94. FAIL(AVERROR(EPERM));
  95. }
  96. proto = avio_find_protocol_name(filename);
  97. proto_len = proto ? strlen(proto) : 0;
  98. if (!memcmp(filename, proto, proto_len) &&
  99. (filename[proto_len] == ':' || filename[proto_len] == ',')) {
  100. url = filename;
  101. filename = NULL;
  102. } else {
  103. url_len = strlen(avf->filename) + strlen(filename) + 16;
  104. if (!(url = av_malloc(url_len)))
  105. FAIL(AVERROR(ENOMEM));
  106. ff_make_absolute_url(url, url_len, avf->filename, filename);
  107. av_freep(&filename);
  108. }
  109. if (cat->nb_files >= *nb_files_alloc) {
  110. size_t n = FFMAX(*nb_files_alloc * 2, 16);
  111. ConcatFile *new_files;
  112. if (n <= cat->nb_files || n > SIZE_MAX / sizeof(*cat->files) ||
  113. !(new_files = av_realloc(cat->files, n * sizeof(*cat->files))))
  114. FAIL(AVERROR(ENOMEM));
  115. cat->files = new_files;
  116. *nb_files_alloc = n;
  117. }
  118. file = &cat->files[cat->nb_files++];
  119. memset(file, 0, sizeof(*file));
  120. *rfile = file;
  121. file->url = url;
  122. file->start_time = AV_NOPTS_VALUE;
  123. file->duration = AV_NOPTS_VALUE;
  124. return 0;
  125. fail:
  126. av_free(url);
  127. av_free(filename);
  128. return ret;
  129. }
  130. static int copy_stream_props(AVStream *st, AVStream *source_st)
  131. {
  132. int ret;
  133. if (st->codec->codec_id || !source_st->codec->codec_id)
  134. return 0;
  135. if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
  136. return ret;
  137. st->r_frame_rate = source_st->r_frame_rate;
  138. st->avg_frame_rate = source_st->avg_frame_rate;
  139. st->time_base = source_st->time_base;
  140. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  141. return 0;
  142. }
  143. static int match_streams_one_to_one(AVFormatContext *avf)
  144. {
  145. ConcatContext *cat = avf->priv_data;
  146. AVStream *st;
  147. int i, ret;
  148. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  149. if (i < avf->nb_streams) {
  150. st = avf->streams[i];
  151. } else {
  152. if (!(st = avformat_new_stream(avf, NULL)))
  153. return AVERROR(ENOMEM);
  154. }
  155. if ((ret = copy_stream_props(st, cat->avf->streams[i])) < 0)
  156. return ret;
  157. cat->cur_file->streams[i].out_stream_index = i;
  158. }
  159. return 0;
  160. }
  161. static int match_streams_exact_id(AVFormatContext *avf)
  162. {
  163. ConcatContext *cat = avf->priv_data;
  164. AVStream *st;
  165. int i, j, ret;
  166. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++) {
  167. st = cat->avf->streams[i];
  168. for (j = 0; j < avf->nb_streams; j++) {
  169. if (avf->streams[j]->id == st->id) {
  170. av_log(avf, AV_LOG_VERBOSE,
  171. "Match slave stream #%d with stream #%d id 0x%x\n",
  172. i, j, st->id);
  173. if ((ret = copy_stream_props(avf->streams[j], st)) < 0)
  174. return ret;
  175. cat->cur_file->streams[i].out_stream_index = j;
  176. }
  177. }
  178. }
  179. return 0;
  180. }
  181. static int match_streams(AVFormatContext *avf)
  182. {
  183. ConcatContext *cat = avf->priv_data;
  184. ConcatStream *map;
  185. int i, ret;
  186. if (cat->cur_file->nb_streams >= cat->avf->nb_streams)
  187. return 0;
  188. map = av_realloc(cat->cur_file->streams,
  189. cat->avf->nb_streams * sizeof(*map));
  190. if (!map)
  191. return AVERROR(ENOMEM);
  192. cat->cur_file->streams = map;
  193. for (i = cat->cur_file->nb_streams; i < cat->avf->nb_streams; i++)
  194. map[i].out_stream_index = -1;
  195. switch (cat->stream_match_mode) {
  196. case MATCH_ONE_TO_ONE:
  197. ret = match_streams_one_to_one(avf);
  198. break;
  199. case MATCH_EXACT_ID:
  200. ret = match_streams_exact_id(avf);
  201. break;
  202. default:
  203. ret = AVERROR_BUG;
  204. }
  205. if (ret < 0)
  206. return ret;
  207. cat->cur_file->nb_streams = cat->avf->nb_streams;
  208. return 0;
  209. }
  210. static int open_file(AVFormatContext *avf, unsigned fileno)
  211. {
  212. ConcatContext *cat = avf->priv_data;
  213. ConcatFile *file = &cat->files[fileno];
  214. int ret;
  215. if (cat->avf)
  216. avformat_close_input(&cat->avf);
  217. cat->avf = avformat_alloc_context();
  218. if (!cat->avf)
  219. return AVERROR(ENOMEM);
  220. cat->avf->interrupt_callback = avf->interrupt_callback;
  221. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  222. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  223. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  224. avformat_close_input(&cat->avf);
  225. return ret;
  226. }
  227. cat->cur_file = file;
  228. if (file->start_time == AV_NOPTS_VALUE)
  229. file->start_time = !fileno ? 0 :
  230. cat->files[fileno - 1].start_time +
  231. cat->files[fileno - 1].duration;
  232. if ((ret = match_streams(avf)) < 0)
  233. return ret;
  234. return 0;
  235. }
  236. static int concat_read_close(AVFormatContext *avf)
  237. {
  238. ConcatContext *cat = avf->priv_data;
  239. unsigned i;
  240. if (cat->avf)
  241. avformat_close_input(&cat->avf);
  242. for (i = 0; i < cat->nb_files; i++) {
  243. av_freep(&cat->files[i].url);
  244. av_freep(&cat->files[i].streams);
  245. }
  246. av_freep(&cat->files);
  247. return 0;
  248. }
  249. static int concat_read_header(AVFormatContext *avf)
  250. {
  251. ConcatContext *cat = avf->priv_data;
  252. uint8_t buf[4096];
  253. uint8_t *cursor, *keyword;
  254. int ret, line = 0, i;
  255. unsigned nb_files_alloc = 0;
  256. ConcatFile *file = NULL;
  257. int64_t time = 0;
  258. while (1) {
  259. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  260. break;
  261. line++;
  262. cursor = buf;
  263. keyword = get_keyword(&cursor);
  264. if (!*keyword || *keyword == '#')
  265. continue;
  266. if (!strcmp(keyword, "file")) {
  267. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  268. if (!filename) {
  269. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  270. FAIL(AVERROR_INVALIDDATA);
  271. }
  272. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  273. FAIL(ret);
  274. } else if (!strcmp(keyword, "duration")) {
  275. char *dur_str = get_keyword(&cursor);
  276. int64_t dur;
  277. if (!file) {
  278. av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
  279. line);
  280. FAIL(AVERROR_INVALIDDATA);
  281. }
  282. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  283. av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
  284. line, dur_str);
  285. FAIL(ret);
  286. }
  287. file->duration = dur;
  288. } else if (!strcmp(keyword, "stream")) {
  289. if (!avformat_new_stream(avf, NULL))
  290. FAIL(AVERROR(ENOMEM));
  291. } else if (!strcmp(keyword, "exact_stream_id")) {
  292. if (!avf->nb_streams) {
  293. av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
  294. line);
  295. FAIL(AVERROR_INVALIDDATA);
  296. }
  297. avf->streams[avf->nb_streams - 1]->id =
  298. strtol(get_keyword(&cursor), NULL, 0);
  299. } else if (!strcmp(keyword, "ffconcat")) {
  300. char *ver_kw = get_keyword(&cursor);
  301. char *ver_val = get_keyword(&cursor);
  302. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  303. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  304. FAIL(AVERROR_INVALIDDATA);
  305. }
  306. if (cat->safe < 0)
  307. cat->safe = 1;
  308. } else {
  309. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  310. line, keyword);
  311. FAIL(AVERROR_INVALIDDATA);
  312. }
  313. }
  314. if (ret < 0)
  315. FAIL(ret);
  316. if (!cat->nb_files)
  317. FAIL(AVERROR_INVALIDDATA);
  318. for (i = 0; i < cat->nb_files; i++) {
  319. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  320. cat->files[i].start_time = time;
  321. else
  322. time = cat->files[i].start_time;
  323. if (cat->files[i].duration == AV_NOPTS_VALUE)
  324. break;
  325. time += cat->files[i].duration;
  326. }
  327. if (i == cat->nb_files) {
  328. avf->duration = time;
  329. cat->seekable = 1;
  330. }
  331. cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
  332. MATCH_ONE_TO_ONE;
  333. if ((ret = open_file(avf, 0)) < 0)
  334. FAIL(ret);
  335. return 0;
  336. fail:
  337. concat_read_close(avf);
  338. return ret;
  339. }
  340. static int open_next_file(AVFormatContext *avf)
  341. {
  342. ConcatContext *cat = avf->priv_data;
  343. unsigned fileno = cat->cur_file - cat->files;
  344. if (cat->cur_file->duration == AV_NOPTS_VALUE)
  345. cat->cur_file->duration = cat->avf->duration;
  346. if (++fileno >= cat->nb_files)
  347. return AVERROR_EOF;
  348. return open_file(avf, fileno);
  349. }
  350. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  351. {
  352. ConcatContext *cat = avf->priv_data;
  353. int ret;
  354. int64_t delta;
  355. ConcatStream *cs;
  356. while (1) {
  357. ret = av_read_frame(cat->avf, pkt);
  358. if (ret == AVERROR_EOF) {
  359. if ((ret = open_next_file(avf)) < 0)
  360. return ret;
  361. continue;
  362. }
  363. if (ret < 0)
  364. return ret;
  365. if ((ret = match_streams(avf)) < 0) {
  366. av_packet_unref(pkt);
  367. return ret;
  368. }
  369. cs = &cat->cur_file->streams[pkt->stream_index];
  370. if (cs->out_stream_index < 0) {
  371. av_packet_unref(pkt);
  372. continue;
  373. }
  374. pkt->stream_index = cs->out_stream_index;
  375. break;
  376. }
  377. delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
  378. AV_TIME_BASE_Q,
  379. cat->avf->streams[pkt->stream_index]->time_base);
  380. if (pkt->pts != AV_NOPTS_VALUE)
  381. pkt->pts += delta;
  382. if (pkt->dts != AV_NOPTS_VALUE)
  383. pkt->dts += delta;
  384. return ret;
  385. }
  386. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  387. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  388. {
  389. *ts = av_rescale_q (* ts, tb_in, tb_out);
  390. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  391. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  392. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  393. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  394. }
  395. static int try_seek(AVFormatContext *avf, int stream,
  396. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  397. {
  398. ConcatContext *cat = avf->priv_data;
  399. int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
  400. ts -= t0;
  401. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  402. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  403. if (stream >= 0) {
  404. if (stream >= cat->avf->nb_streams)
  405. return AVERROR(EIO);
  406. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  407. &min_ts, &ts, &max_ts);
  408. }
  409. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  410. }
  411. static int real_seek(AVFormatContext *avf, int stream,
  412. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  413. {
  414. ConcatContext *cat = avf->priv_data;
  415. int ret, left, right;
  416. if (stream >= 0) {
  417. if (stream >= avf->nb_streams)
  418. return AVERROR(EINVAL);
  419. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  420. &min_ts, &ts, &max_ts);
  421. }
  422. left = 0;
  423. right = cat->nb_files;
  424. while (right - left > 1) {
  425. int mid = (left + right) / 2;
  426. if (ts < cat->files[mid].start_time)
  427. right = mid;
  428. else
  429. left = mid;
  430. }
  431. if ((ret = open_file(avf, left)) < 0)
  432. return ret;
  433. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  434. if (ret < 0 &&
  435. left < cat->nb_files - 1 &&
  436. cat->files[left + 1].start_time < max_ts) {
  437. if ((ret = open_file(avf, left + 1)) < 0)
  438. return ret;
  439. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  440. }
  441. return ret;
  442. }
  443. static int concat_seek(AVFormatContext *avf, int stream,
  444. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  445. {
  446. ConcatContext *cat = avf->priv_data;
  447. ConcatFile *cur_file_saved = cat->cur_file;
  448. AVFormatContext *cur_avf_saved = cat->avf;
  449. int ret;
  450. if (!cat->seekable)
  451. return AVERROR(ESPIPE); /* XXX: can we use it? */
  452. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  453. return AVERROR(ENOSYS);
  454. cat->avf = NULL;
  455. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  456. if (cat->avf)
  457. avformat_close_input(&cat->avf);
  458. cat->avf = cur_avf_saved;
  459. cat->cur_file = cur_file_saved;
  460. } else {
  461. avformat_close_input(&cur_avf_saved);
  462. }
  463. return ret;
  464. }
  465. #define OFFSET(x) offsetof(ConcatContext, x)
  466. #define DEC AV_OPT_FLAG_DECODING_PARAM
  467. static const AVOption options[] = {
  468. { "safe", "enable safe mode",
  469. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  470. { NULL }
  471. };
  472. static const AVClass concat_class = {
  473. .class_name = "concat demuxer",
  474. .item_name = av_default_item_name,
  475. .option = options,
  476. .version = LIBAVUTIL_VERSION_INT,
  477. };
  478. AVInputFormat ff_concat_demuxer = {
  479. .name = "concat",
  480. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  481. .priv_data_size = sizeof(ConcatContext),
  482. .read_probe = concat_probe,
  483. .read_header = concat_read_header,
  484. .read_packet = concat_read_packet,
  485. .read_close = concat_read_close,
  486. .read_seek2 = concat_seek,
  487. .priv_class = &concat_class,
  488. };