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.

637 lines
19KB

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