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.

503 lines
15KB

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