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.

636 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. if ((ret = ff_copy_whitelists(cat->avf, avf)) < 0)
  259. return ret;
  260. if ((ret = avformat_open_input(&cat->avf, file->url, NULL, NULL)) < 0 ||
  261. (ret = avformat_find_stream_info(cat->avf, NULL)) < 0) {
  262. av_log(avf, AV_LOG_ERROR, "Impossible to open '%s'\n", file->url);
  263. avformat_close_input(&cat->avf);
  264. return ret;
  265. }
  266. cat->cur_file = file;
  267. if (file->start_time == AV_NOPTS_VALUE)
  268. file->start_time = !fileno ? 0 :
  269. cat->files[fileno - 1].start_time +
  270. cat->files[fileno - 1].duration;
  271. if ((ret = match_streams(avf)) < 0)
  272. return ret;
  273. return 0;
  274. }
  275. static int concat_read_close(AVFormatContext *avf)
  276. {
  277. ConcatContext *cat = avf->priv_data;
  278. unsigned i;
  279. if (cat->avf)
  280. avformat_close_input(&cat->avf);
  281. for (i = 0; i < cat->nb_files; i++) {
  282. av_freep(&cat->files[i].url);
  283. av_freep(&cat->files[i].streams);
  284. }
  285. av_freep(&cat->files);
  286. return 0;
  287. }
  288. static int concat_read_header(AVFormatContext *avf)
  289. {
  290. ConcatContext *cat = avf->priv_data;
  291. uint8_t buf[4096];
  292. uint8_t *cursor, *keyword;
  293. int ret, line = 0, i;
  294. unsigned nb_files_alloc = 0;
  295. ConcatFile *file = NULL;
  296. int64_t time = 0;
  297. while (1) {
  298. if ((ret = ff_get_line(avf->pb, buf, sizeof(buf))) <= 0)
  299. break;
  300. line++;
  301. cursor = buf;
  302. keyword = get_keyword(&cursor);
  303. if (!*keyword || *keyword == '#')
  304. continue;
  305. if (!strcmp(keyword, "file")) {
  306. char *filename = av_get_token((const char **)&cursor, SPACE_CHARS);
  307. if (!filename) {
  308. av_log(avf, AV_LOG_ERROR, "Line %d: filename required\n", line);
  309. FAIL(AVERROR_INVALIDDATA);
  310. }
  311. if ((ret = add_file(avf, filename, &file, &nb_files_alloc)) < 0)
  312. goto fail;
  313. } else if (!strcmp(keyword, "duration")) {
  314. char *dur_str = get_keyword(&cursor);
  315. int64_t dur;
  316. if (!file) {
  317. av_log(avf, AV_LOG_ERROR, "Line %d: duration without file\n",
  318. line);
  319. FAIL(AVERROR_INVALIDDATA);
  320. }
  321. if ((ret = av_parse_time(&dur, dur_str, 1)) < 0) {
  322. av_log(avf, AV_LOG_ERROR, "Line %d: invalid duration '%s'\n",
  323. line, dur_str);
  324. goto fail;
  325. }
  326. file->duration = dur;
  327. } else if (!strcmp(keyword, "stream")) {
  328. if (!avformat_new_stream(avf, NULL))
  329. FAIL(AVERROR(ENOMEM));
  330. } else if (!strcmp(keyword, "exact_stream_id")) {
  331. if (!avf->nb_streams) {
  332. av_log(avf, AV_LOG_ERROR, "Line %d: exact_stream_id without stream\n",
  333. line);
  334. FAIL(AVERROR_INVALIDDATA);
  335. }
  336. avf->streams[avf->nb_streams - 1]->id =
  337. strtol(get_keyword(&cursor), NULL, 0);
  338. } else if (!strcmp(keyword, "ffconcat")) {
  339. char *ver_kw = get_keyword(&cursor);
  340. char *ver_val = get_keyword(&cursor);
  341. if (strcmp(ver_kw, "version") || strcmp(ver_val, "1.0")) {
  342. av_log(avf, AV_LOG_ERROR, "Line %d: invalid version\n", line);
  343. FAIL(AVERROR_INVALIDDATA);
  344. }
  345. if (cat->safe < 0)
  346. cat->safe = 1;
  347. } else {
  348. av_log(avf, AV_LOG_ERROR, "Line %d: unknown keyword '%s'\n",
  349. line, keyword);
  350. FAIL(AVERROR_INVALIDDATA);
  351. }
  352. }
  353. if (ret < 0)
  354. goto fail;
  355. if (!cat->nb_files)
  356. FAIL(AVERROR_INVALIDDATA);
  357. for (i = 0; i < cat->nb_files; i++) {
  358. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  359. cat->files[i].start_time = time;
  360. else
  361. time = cat->files[i].start_time;
  362. if (cat->files[i].duration == AV_NOPTS_VALUE)
  363. break;
  364. time += cat->files[i].duration;
  365. }
  366. if (i == cat->nb_files) {
  367. avf->duration = time;
  368. cat->seekable = 1;
  369. }
  370. cat->stream_match_mode = avf->nb_streams ? MATCH_EXACT_ID :
  371. MATCH_ONE_TO_ONE;
  372. if ((ret = open_file(avf, 0)) < 0)
  373. goto fail;
  374. return 0;
  375. fail:
  376. concat_read_close(avf);
  377. return ret;
  378. }
  379. static int open_next_file(AVFormatContext *avf)
  380. {
  381. ConcatContext *cat = avf->priv_data;
  382. unsigned fileno = cat->cur_file - cat->files;
  383. if (cat->cur_file->duration == AV_NOPTS_VALUE)
  384. cat->cur_file->duration = cat->avf->duration;
  385. if (++fileno >= cat->nb_files)
  386. return AVERROR_EOF;
  387. return open_file(avf, fileno);
  388. }
  389. static int filter_packet(AVFormatContext *avf, ConcatStream *cs, AVPacket *pkt)
  390. {
  391. AVStream *st = avf->streams[cs->out_stream_index];
  392. AVBitStreamFilterContext *bsf;
  393. AVPacket pkt2;
  394. int ret;
  395. av_assert0(cs->out_stream_index >= 0);
  396. for (bsf = cs->bsf; bsf; bsf = bsf->next) {
  397. pkt2 = *pkt;
  398. ret = av_bitstream_filter_filter(bsf, st->codec, NULL,
  399. &pkt2.data, &pkt2.size,
  400. pkt->data, pkt->size,
  401. !!(pkt->flags & AV_PKT_FLAG_KEY));
  402. if (ret < 0) {
  403. av_packet_unref(pkt);
  404. return ret;
  405. }
  406. av_assert0(pkt2.buf);
  407. if (ret == 0 && pkt2.data != pkt->data) {
  408. if ((ret = av_copy_packet(&pkt2, pkt)) < 0) {
  409. av_free(pkt2.data);
  410. return ret;
  411. }
  412. ret = 1;
  413. }
  414. if (ret > 0) {
  415. av_free_packet(pkt);
  416. pkt2.buf = av_buffer_create(pkt2.data, pkt2.size,
  417. av_buffer_default_free, NULL, 0);
  418. if (!pkt2.buf) {
  419. av_free(pkt2.data);
  420. return AVERROR(ENOMEM);
  421. }
  422. }
  423. *pkt = pkt2;
  424. }
  425. return 0;
  426. }
  427. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  428. {
  429. ConcatContext *cat = avf->priv_data;
  430. int ret;
  431. int64_t delta;
  432. ConcatStream *cs;
  433. while (1) {
  434. ret = av_read_frame(cat->avf, pkt);
  435. if (ret == AVERROR_EOF) {
  436. if ((ret = open_next_file(avf)) < 0)
  437. return ret;
  438. continue;
  439. }
  440. if (ret < 0)
  441. return ret;
  442. if ((ret = match_streams(avf)) < 0) {
  443. av_packet_unref(pkt);
  444. return ret;
  445. }
  446. cs = &cat->cur_file->streams[pkt->stream_index];
  447. if (cs->out_stream_index < 0) {
  448. av_packet_unref(pkt);
  449. continue;
  450. }
  451. pkt->stream_index = cs->out_stream_index;
  452. break;
  453. }
  454. if ((ret = filter_packet(avf, cs, pkt)))
  455. return ret;
  456. delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
  457. AV_TIME_BASE_Q,
  458. cat->avf->streams[pkt->stream_index]->time_base);
  459. if (pkt->pts != AV_NOPTS_VALUE)
  460. pkt->pts += delta;
  461. if (pkt->dts != AV_NOPTS_VALUE)
  462. pkt->dts += delta;
  463. return ret;
  464. }
  465. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  466. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  467. {
  468. *ts = av_rescale_q (* ts, tb_in, tb_out);
  469. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  470. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  471. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  472. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  473. }
  474. static int try_seek(AVFormatContext *avf, int stream,
  475. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  476. {
  477. ConcatContext *cat = avf->priv_data;
  478. int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
  479. ts -= t0;
  480. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  481. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  482. if (stream >= 0) {
  483. if (stream >= cat->avf->nb_streams)
  484. return AVERROR(EIO);
  485. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  486. &min_ts, &ts, &max_ts);
  487. }
  488. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  489. }
  490. static int real_seek(AVFormatContext *avf, int stream,
  491. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  492. {
  493. ConcatContext *cat = avf->priv_data;
  494. int ret, left, right;
  495. if (stream >= 0) {
  496. if (stream >= avf->nb_streams)
  497. return AVERROR(EINVAL);
  498. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  499. &min_ts, &ts, &max_ts);
  500. }
  501. left = 0;
  502. right = cat->nb_files;
  503. while (right - left > 1) {
  504. int mid = (left + right) / 2;
  505. if (ts < cat->files[mid].start_time)
  506. right = mid;
  507. else
  508. left = mid;
  509. }
  510. if ((ret = open_file(avf, left)) < 0)
  511. return ret;
  512. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  513. if (ret < 0 &&
  514. left < cat->nb_files - 1 &&
  515. cat->files[left + 1].start_time < max_ts) {
  516. if ((ret = open_file(avf, left + 1)) < 0)
  517. return ret;
  518. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  519. }
  520. return ret;
  521. }
  522. static int concat_seek(AVFormatContext *avf, int stream,
  523. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  524. {
  525. ConcatContext *cat = avf->priv_data;
  526. ConcatFile *cur_file_saved = cat->cur_file;
  527. AVFormatContext *cur_avf_saved = cat->avf;
  528. int ret;
  529. if (!cat->seekable)
  530. return AVERROR(ESPIPE); /* XXX: can we use it? */
  531. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  532. return AVERROR(ENOSYS);
  533. cat->avf = NULL;
  534. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  535. if (cat->avf)
  536. avformat_close_input(&cat->avf);
  537. cat->avf = cur_avf_saved;
  538. cat->cur_file = cur_file_saved;
  539. } else {
  540. avformat_close_input(&cur_avf_saved);
  541. }
  542. return ret;
  543. }
  544. #define OFFSET(x) offsetof(ConcatContext, x)
  545. #define DEC AV_OPT_FLAG_DECODING_PARAM
  546. static const AVOption options[] = {
  547. { "safe", "enable safe mode",
  548. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  549. { "auto_convert", "automatically convert bitstream format",
  550. OFFSET(auto_convert), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  551. { NULL }
  552. };
  553. static const AVClass concat_class = {
  554. .class_name = "concat demuxer",
  555. .item_name = av_default_item_name,
  556. .option = options,
  557. .version = LIBAVUTIL_VERSION_INT,
  558. };
  559. AVInputFormat ff_concat_demuxer = {
  560. .name = "concat",
  561. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  562. .priv_data_size = sizeof(ConcatContext),
  563. .read_probe = concat_probe,
  564. .read_header = concat_read_header,
  565. .read_packet = concat_read_packet,
  566. .read_close = concat_read_close,
  567. .read_seek2 = concat_seek,
  568. .priv_class = &concat_class,
  569. };