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.

406 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. for (i = 0; i < cat->nb_files; i++) {
  198. if (cat->files[i].start_time == AV_NOPTS_VALUE)
  199. cat->files[i].start_time = time;
  200. else
  201. time = cat->files[i].start_time;
  202. if (cat->files[i].duration == AV_NOPTS_VALUE)
  203. break;
  204. time += cat->files[i].duration;
  205. }
  206. if (i == cat->nb_files) {
  207. avf->duration = time;
  208. cat->seekable = 1;
  209. }
  210. if ((ret = open_file(avf, 0)) < 0)
  211. FAIL(ret);
  212. for (i = 0; i < cat->avf->nb_streams; i++) {
  213. if (!(st = avformat_new_stream(avf, NULL)))
  214. FAIL(AVERROR(ENOMEM));
  215. source_st = cat->avf->streams[i];
  216. if ((ret = avcodec_copy_context(st->codec, source_st->codec)) < 0)
  217. FAIL(ret);
  218. st->r_frame_rate = source_st->r_frame_rate;
  219. st->avg_frame_rate = source_st->avg_frame_rate;
  220. st->time_base = source_st->time_base;
  221. st->sample_aspect_ratio = source_st->sample_aspect_ratio;
  222. }
  223. return 0;
  224. fail:
  225. concat_read_close(avf);
  226. return ret;
  227. }
  228. static int open_next_file(AVFormatContext *avf)
  229. {
  230. ConcatContext *cat = avf->priv_data;
  231. unsigned fileno = cat->cur_file - cat->files;
  232. if (cat->cur_file->duration == AV_NOPTS_VALUE)
  233. cat->cur_file->duration = cat->avf->duration;
  234. if (++fileno >= cat->nb_files)
  235. return AVERROR_EOF;
  236. return open_file(avf, fileno);
  237. }
  238. static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)
  239. {
  240. ConcatContext *cat = avf->priv_data;
  241. int ret;
  242. int64_t delta;
  243. while (1) {
  244. if ((ret = av_read_frame(cat->avf, pkt)) != AVERROR_EOF ||
  245. (ret = open_next_file(avf)) < 0)
  246. break;
  247. }
  248. delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,
  249. AV_TIME_BASE_Q,
  250. cat->avf->streams[pkt->stream_index]->time_base);
  251. if (pkt->pts != AV_NOPTS_VALUE)
  252. pkt->pts += delta;
  253. if (pkt->dts != AV_NOPTS_VALUE)
  254. pkt->dts += delta;
  255. return ret;
  256. }
  257. static void rescale_interval(AVRational tb_in, AVRational tb_out,
  258. int64_t *min_ts, int64_t *ts, int64_t *max_ts)
  259. {
  260. *ts = av_rescale_q (* ts, tb_in, tb_out);
  261. *min_ts = av_rescale_q_rnd(*min_ts, tb_in, tb_out,
  262. AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
  263. *max_ts = av_rescale_q_rnd(*max_ts, tb_in, tb_out,
  264. AV_ROUND_DOWN | AV_ROUND_PASS_MINMAX);
  265. }
  266. static int try_seek(AVFormatContext *avf, int stream,
  267. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  268. {
  269. ConcatContext *cat = avf->priv_data;
  270. int64_t t0 = cat->cur_file->start_time - cat->avf->start_time;
  271. ts -= t0;
  272. min_ts = min_ts == INT64_MIN ? INT64_MIN : min_ts - t0;
  273. max_ts = max_ts == INT64_MAX ? INT64_MAX : max_ts - t0;
  274. if (stream >= 0) {
  275. if (stream >= cat->avf->nb_streams)
  276. return AVERROR(EIO);
  277. rescale_interval(AV_TIME_BASE_Q, cat->avf->streams[stream]->time_base,
  278. &min_ts, &ts, &max_ts);
  279. }
  280. return avformat_seek_file(cat->avf, stream, min_ts, ts, max_ts, flags);
  281. }
  282. static int real_seek(AVFormatContext *avf, int stream,
  283. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  284. {
  285. ConcatContext *cat = avf->priv_data;
  286. int ret, left, right;
  287. if (stream >= 0) {
  288. if (stream >= avf->nb_streams)
  289. return AVERROR(EINVAL);
  290. rescale_interval(avf->streams[stream]->time_base, AV_TIME_BASE_Q,
  291. &min_ts, &ts, &max_ts);
  292. }
  293. left = 0;
  294. right = cat->nb_files;
  295. while (right - left > 1) {
  296. int mid = (left + right) / 2;
  297. if (ts < cat->files[mid].start_time)
  298. right = mid;
  299. else
  300. left = mid;
  301. }
  302. if ((ret = open_file(avf, left)) < 0)
  303. return ret;
  304. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  305. if (ret < 0 &&
  306. left < cat->nb_files - 1 &&
  307. cat->files[left + 1].start_time < max_ts) {
  308. if ((ret = open_file(avf, left + 1)) < 0)
  309. return ret;
  310. ret = try_seek(avf, stream, min_ts, ts, max_ts, flags);
  311. }
  312. return ret;
  313. }
  314. static int concat_seek(AVFormatContext *avf, int stream,
  315. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  316. {
  317. ConcatContext *cat = avf->priv_data;
  318. ConcatFile *cur_file_saved = cat->cur_file;
  319. AVFormatContext *cur_avf_saved = cat->avf;
  320. int ret;
  321. if (!cat->seekable)
  322. return AVERROR(ESPIPE); /* XXX: can we use it? */
  323. if (flags & (AVSEEK_FLAG_BYTE | AVSEEK_FLAG_FRAME))
  324. return AVERROR(ENOSYS);
  325. cat->avf = NULL;
  326. if ((ret = real_seek(avf, stream, min_ts, ts, max_ts, flags)) < 0) {
  327. if (cat->avf)
  328. avformat_close_input(&cat->avf);
  329. cat->avf = cur_avf_saved;
  330. cat->cur_file = cur_file_saved;
  331. } else {
  332. avformat_close_input(&cur_avf_saved);
  333. }
  334. return ret;
  335. }
  336. #define OFFSET(x) offsetof(ConcatContext, x)
  337. #define DEC AV_OPT_FLAG_DECODING_PARAM
  338. static const AVOption options[] = {
  339. { "safe", "enable safe mode",
  340. OFFSET(safe), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, DEC },
  341. { NULL }
  342. };
  343. static const AVClass concat_class = {
  344. .class_name = "concat demuxer",
  345. .item_name = av_default_item_name,
  346. .option = options,
  347. .version = LIBAVUTIL_VERSION_INT,
  348. };
  349. AVInputFormat ff_concat_demuxer = {
  350. .name = "concat",
  351. .long_name = NULL_IF_CONFIG_SMALL("Virtual concatenation script"),
  352. .priv_data_size = sizeof(ConcatContext),
  353. .read_probe = concat_probe,
  354. .read_header = concat_read_header,
  355. .read_packet = concat_read_packet,
  356. .read_close = concat_read_close,
  357. .read_seek2 = concat_seek,
  358. .priv_class = &concat_class,
  359. };