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.

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