avformat.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. /*
  2. * Various functions used by both muxers and demuxers
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include <math.h>
  22. #include "libavutil/avassert.h"
  23. #include "libavutil/avstring.h"
  24. #include "libavutil/channel_layout.h"
  25. #include "libavutil/frame.h"
  26. #include "libavutil/iamf.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/mem.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/pixfmt.h"
  31. #include "libavutil/samplefmt.h"
  32. #include "libavcodec/avcodec.h"
  33. #include "libavcodec/codec.h"
  34. #include "libavcodec/bsf.h"
  35. #include "libavcodec/codec_desc.h"
  36. #include "libavcodec/packet_internal.h"
  37. #include "avformat.h"
  38. #include "avformat_internal.h"
  39. #include "avio.h"
  40. #include "demux.h"
  41. #include "mux.h"
  42. #include "internal.h"
  43. void ff_free_stream(AVStream **pst)
  44. {
  45. AVStream *st = *pst;
  46. FFStream *const sti = ffstream(st);
  47. if (!st)
  48. return;
  49. #if FF_API_AVSTREAM_SIDE_DATA
  50. FF_DISABLE_DEPRECATION_WARNINGS
  51. for (int i = 0; i < st->nb_side_data; i++)
  52. av_freep(&st->side_data[i].data);
  53. av_freep(&st->side_data);
  54. FF_ENABLE_DEPRECATION_WARNINGS
  55. #endif
  56. if (st->attached_pic.data)
  57. av_packet_unref(&st->attached_pic);
  58. av_parser_close(sti->parser);
  59. avcodec_free_context(&sti->avctx);
  60. av_bsf_free(&sti->bsfc);
  61. av_freep(&sti->index_entries);
  62. av_freep(&sti->probe_data.buf);
  63. av_bsf_free(&sti->extract_extradata.bsf);
  64. if (sti->info) {
  65. av_freep(&sti->info->duration_error);
  66. av_freep(&sti->info);
  67. }
  68. av_dict_free(&st->metadata);
  69. avcodec_parameters_free(&st->codecpar);
  70. av_freep(&st->priv_data);
  71. av_freep(pst);
  72. }
  73. void ff_free_stream_group(AVStreamGroup **pstg)
  74. {
  75. AVStreamGroup *stg = *pstg;
  76. if (!stg)
  77. return;
  78. av_freep(&stg->streams);
  79. av_dict_free(&stg->metadata);
  80. av_freep(&stg->priv_data);
  81. switch (stg->type) {
  82. case AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT: {
  83. av_iamf_audio_element_free(&stg->params.iamf_audio_element);
  84. break;
  85. }
  86. case AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION: {
  87. av_iamf_mix_presentation_free(&stg->params.iamf_mix_presentation);
  88. break;
  89. }
  90. case AV_STREAM_GROUP_PARAMS_TILE_GRID:
  91. av_opt_free(stg->params.tile_grid);
  92. av_freep(&stg->params.tile_grid->offsets);
  93. av_packet_side_data_free(&stg->params.tile_grid->coded_side_data,
  94. &stg->params.tile_grid->nb_coded_side_data);
  95. av_freep(&stg->params.tile_grid);
  96. break;
  97. case AV_STREAM_GROUP_PARAMS_LCEVC:
  98. av_opt_free(stg->params.lcevc);
  99. av_freep(&stg->params.lcevc);
  100. break;
  101. default:
  102. break;
  103. }
  104. av_freep(pstg);
  105. }
  106. void ff_remove_stream(AVFormatContext *s, AVStream *st)
  107. {
  108. av_assert0(s->nb_streams>0);
  109. av_assert0(s->streams[ s->nb_streams - 1 ] == st);
  110. ff_free_stream(&s->streams[ --s->nb_streams ]);
  111. }
  112. void ff_remove_stream_group(AVFormatContext *s, AVStreamGroup *stg)
  113. {
  114. av_assert0(s->nb_stream_groups > 0);
  115. av_assert0(s->stream_groups[ s->nb_stream_groups - 1 ] == stg);
  116. ff_free_stream_group(&s->stream_groups[ --s->nb_stream_groups ]);
  117. }
  118. /* XXX: suppress the packet queue */
  119. void ff_flush_packet_queue(AVFormatContext *s)
  120. {
  121. FFFormatContext *const si = ffformatcontext(s);
  122. avpriv_packet_list_free(&si->parse_queue);
  123. avpriv_packet_list_free(&si->packet_buffer);
  124. avpriv_packet_list_free(&si->raw_packet_buffer);
  125. si->raw_packet_buffer_size = 0;
  126. }
  127. void avformat_free_context(AVFormatContext *s)
  128. {
  129. FFFormatContext *si;
  130. if (!s)
  131. return;
  132. si = ffformatcontext(s);
  133. if (s->oformat && ffofmt(s->oformat)->deinit && si->initialized)
  134. ffofmt(s->oformat)->deinit(s);
  135. av_opt_free(s);
  136. if (s->iformat && s->iformat->priv_class && s->priv_data)
  137. av_opt_free(s->priv_data);
  138. if (s->oformat && s->oformat->priv_class && s->priv_data)
  139. av_opt_free(s->priv_data);
  140. for (unsigned i = 0; i < s->nb_streams; i++)
  141. ff_free_stream(&s->streams[i]);
  142. for (unsigned i = 0; i < s->nb_stream_groups; i++)
  143. ff_free_stream_group(&s->stream_groups[i]);
  144. s->nb_stream_groups = 0;
  145. s->nb_streams = 0;
  146. for (unsigned i = 0; i < s->nb_programs; i++) {
  147. av_dict_free(&s->programs[i]->metadata);
  148. av_freep(&s->programs[i]->stream_index);
  149. av_freep(&s->programs[i]);
  150. }
  151. s->nb_programs = 0;
  152. av_freep(&s->programs);
  153. av_freep(&s->priv_data);
  154. while (s->nb_chapters--) {
  155. av_dict_free(&s->chapters[s->nb_chapters]->metadata);
  156. av_freep(&s->chapters[s->nb_chapters]);
  157. }
  158. av_freep(&s->chapters);
  159. av_dict_free(&s->metadata);
  160. av_dict_free(&si->id3v2_meta);
  161. av_packet_free(&si->pkt);
  162. av_packet_free(&si->parse_pkt);
  163. av_freep(&s->streams);
  164. av_freep(&s->stream_groups);
  165. ff_flush_packet_queue(s);
  166. av_freep(&s->url);
  167. av_free(s);
  168. }
  169. #if FF_API_AVSTREAM_SIDE_DATA
  170. FF_DISABLE_DEPRECATION_WARNINGS
  171. uint8_t *av_stream_get_side_data(const AVStream *st,
  172. enum AVPacketSideDataType type, size_t *size)
  173. {
  174. for (int i = 0; i < st->nb_side_data; i++) {
  175. if (st->side_data[i].type == type) {
  176. if (size)
  177. *size = st->side_data[i].size;
  178. return st->side_data[i].data;
  179. }
  180. }
  181. if (size)
  182. *size = 0;
  183. return NULL;
  184. }
  185. int av_stream_add_side_data(AVStream *st, enum AVPacketSideDataType type,
  186. uint8_t *data, size_t size)
  187. {
  188. AVPacketSideData *sd, *tmp;
  189. for (int i = 0; i < st->nb_side_data; i++) {
  190. sd = &st->side_data[i];
  191. if (sd->type == type) {
  192. av_freep(&sd->data);
  193. sd->data = data;
  194. sd->size = size;
  195. return 0;
  196. }
  197. }
  198. if (st->nb_side_data + 1U > FFMIN(INT_MAX, SIZE_MAX / sizeof(*tmp)))
  199. return AVERROR(ERANGE);
  200. tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));
  201. if (!tmp) {
  202. return AVERROR(ENOMEM);
  203. }
  204. st->side_data = tmp;
  205. st->nb_side_data++;
  206. sd = &st->side_data[st->nb_side_data - 1];
  207. sd->type = type;
  208. sd->data = data;
  209. sd->size = size;
  210. return 0;
  211. }
  212. uint8_t *av_stream_new_side_data(AVStream *st, enum AVPacketSideDataType type,
  213. size_t size)
  214. {
  215. int ret;
  216. uint8_t *data = av_malloc(size);
  217. if (!data)
  218. return NULL;
  219. ret = av_stream_add_side_data(st, type, data, size);
  220. if (ret < 0) {
  221. av_freep(&data);
  222. return NULL;
  223. }
  224. return data;
  225. }
  226. FF_ENABLE_DEPRECATION_WARNINGS
  227. #endif
  228. /**
  229. * Copy all stream parameters from source to destination stream, with the
  230. * exception of the index field, which is usually set by avformat_new_stream().
  231. *
  232. * @param dst pointer to destination AVStream
  233. * @param src pointer to source AVStream
  234. * @return >=0 on success, AVERROR code on error
  235. */
  236. static int stream_params_copy(AVStream *dst, const AVStream *src)
  237. {
  238. int ret;
  239. dst->id = src->id;
  240. dst->time_base = src->time_base;
  241. dst->start_time = src->start_time;
  242. dst->duration = src->duration;
  243. dst->nb_frames = src->nb_frames;
  244. dst->disposition = src->disposition;
  245. dst->discard = src->discard;
  246. dst->sample_aspect_ratio = src->sample_aspect_ratio;
  247. dst->avg_frame_rate = src->avg_frame_rate;
  248. dst->event_flags = src->event_flags;
  249. dst->r_frame_rate = src->r_frame_rate;
  250. dst->pts_wrap_bits = src->pts_wrap_bits;
  251. av_dict_free(&dst->metadata);
  252. ret = av_dict_copy(&dst->metadata, src->metadata, 0);
  253. if (ret < 0)
  254. return ret;
  255. ret = avcodec_parameters_copy(dst->codecpar, src->codecpar);
  256. if (ret < 0)
  257. return ret;
  258. av_packet_unref(&dst->attached_pic);
  259. if (src->attached_pic.data) {
  260. ret = av_packet_ref(&dst->attached_pic, &src->attached_pic);
  261. if (ret < 0)
  262. return ret;
  263. }
  264. return 0;
  265. }
  266. AVStream *ff_stream_clone(AVFormatContext *dst_ctx, const AVStream *src)
  267. {
  268. AVStream *st;
  269. int ret;
  270. st = avformat_new_stream(dst_ctx, NULL);
  271. if (!st)
  272. return NULL;
  273. ret = stream_params_copy(st, src);
  274. if (ret < 0) {
  275. ff_remove_stream(dst_ctx, st);
  276. return NULL;
  277. }
  278. return st;
  279. }
  280. const char *avformat_stream_group_name(enum AVStreamGroupParamsType type)
  281. {
  282. switch(type) {
  283. case AV_STREAM_GROUP_PARAMS_IAMF_AUDIO_ELEMENT: return "IAMF Audio Element";
  284. case AV_STREAM_GROUP_PARAMS_IAMF_MIX_PRESENTATION: return "IAMF Mix Presentation";
  285. case AV_STREAM_GROUP_PARAMS_TILE_GRID: return "Tile Grid";
  286. case AV_STREAM_GROUP_PARAMS_LCEVC: return "LCEVC (Split video and enhancement)";
  287. }
  288. return NULL;
  289. }
  290. AVProgram *av_new_program(AVFormatContext *ac, int id)
  291. {
  292. AVProgram *program = NULL;
  293. int ret;
  294. av_log(ac, AV_LOG_TRACE, "new_program: id=0x%04x\n", id);
  295. for (unsigned i = 0; i < ac->nb_programs; i++)
  296. if (ac->programs[i]->id == id)
  297. program = ac->programs[i];
  298. if (!program) {
  299. program = av_mallocz(sizeof(*program));
  300. if (!program)
  301. return NULL;
  302. ret = av_dynarray_add_nofree(&ac->programs, &ac->nb_programs, program);
  303. if (ret < 0) {
  304. av_free(program);
  305. return NULL;
  306. }
  307. program->discard = AVDISCARD_NONE;
  308. program->pmt_version = -1;
  309. program->id = id;
  310. program->pts_wrap_reference = AV_NOPTS_VALUE;
  311. program->pts_wrap_behavior = AV_PTS_WRAP_IGNORE;
  312. program->start_time =
  313. program->end_time = AV_NOPTS_VALUE;
  314. }
  315. return program;
  316. }
  317. void av_program_add_stream_index(AVFormatContext *ac, int progid, unsigned idx)
  318. {
  319. AVProgram *program = NULL;
  320. void *tmp;
  321. if (idx >= ac->nb_streams) {
  322. av_log(ac, AV_LOG_ERROR, "stream index %d is not valid\n", idx);
  323. return;
  324. }
  325. for (unsigned i = 0; i < ac->nb_programs; i++) {
  326. if (ac->programs[i]->id != progid)
  327. continue;
  328. program = ac->programs[i];
  329. for (unsigned j = 0; j < program->nb_stream_indexes; j++)
  330. if (program->stream_index[j] == idx)
  331. return;
  332. tmp = av_realloc_array(program->stream_index, program->nb_stream_indexes+1, sizeof(unsigned int));
  333. if (!tmp)
  334. return;
  335. program->stream_index = tmp;
  336. program->stream_index[program->nb_stream_indexes++] = idx;
  337. return;
  338. }
  339. }
  340. AVProgram *av_find_program_from_stream(AVFormatContext *ic, AVProgram *last, int s)
  341. {
  342. for (unsigned i = 0; i < ic->nb_programs; i++) {
  343. if (ic->programs[i] == last) {
  344. last = NULL;
  345. } else {
  346. if (!last)
  347. for (unsigned j = 0; j < ic->programs[i]->nb_stream_indexes; j++)
  348. if (ic->programs[i]->stream_index[j] == s)
  349. return ic->programs[i];
  350. }
  351. }
  352. return NULL;
  353. }
  354. int av_find_default_stream_index(AVFormatContext *s)
  355. {
  356. int best_stream = 0;
  357. int best_score = INT_MIN;
  358. if (s->nb_streams <= 0)
  359. return -1;
  360. for (unsigned i = 0; i < s->nb_streams; i++) {
  361. const AVStream *const st = s->streams[i];
  362. const FFStream *const sti = cffstream(st);
  363. int score = 0;
  364. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  365. if (st->disposition & AV_DISPOSITION_ATTACHED_PIC)
  366. score -= 400;
  367. if (st->codecpar->width && st->codecpar->height)
  368. score += 50;
  369. score+= 25;
  370. }
  371. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  372. if (st->codecpar->sample_rate)
  373. score += 50;
  374. }
  375. if (sti->codec_info_nb_frames)
  376. score += 12;
  377. if (st->discard != AVDISCARD_ALL)
  378. score += 200;
  379. if (score > best_score) {
  380. best_score = score;
  381. best_stream = i;
  382. }
  383. }
  384. return best_stream;
  385. }
  386. int av_find_best_stream(AVFormatContext *ic, enum AVMediaType type,
  387. int wanted_stream_nb, int related_stream,
  388. const AVCodec **decoder_ret, int flags)
  389. {
  390. int nb_streams = ic->nb_streams;
  391. int ret = AVERROR_STREAM_NOT_FOUND;
  392. int best_count = -1, best_multiframe = -1, best_disposition = -1;
  393. int count, multiframe, disposition;
  394. int64_t best_bitrate = -1;
  395. int64_t bitrate;
  396. unsigned *program = NULL;
  397. const AVCodec *decoder = NULL, *best_decoder = NULL;
  398. if (related_stream >= 0 && wanted_stream_nb < 0) {
  399. AVProgram *p = av_find_program_from_stream(ic, NULL, related_stream);
  400. if (p) {
  401. program = p->stream_index;
  402. nb_streams = p->nb_stream_indexes;
  403. }
  404. }
  405. for (unsigned i = 0; i < nb_streams; i++) {
  406. int real_stream_index = program ? program[i] : i;
  407. AVStream *st = ic->streams[real_stream_index];
  408. AVCodecParameters *par = st->codecpar;
  409. if (par->codec_type != type)
  410. continue;
  411. if (wanted_stream_nb >= 0 && real_stream_index != wanted_stream_nb)
  412. continue;
  413. if (type == AVMEDIA_TYPE_AUDIO && !(par->ch_layout.nb_channels && par->sample_rate))
  414. continue;
  415. if (decoder_ret) {
  416. decoder = ff_find_decoder(ic, st, par->codec_id);
  417. if (!decoder) {
  418. if (ret < 0)
  419. ret = AVERROR_DECODER_NOT_FOUND;
  420. continue;
  421. }
  422. }
  423. disposition = !(st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED))
  424. + !! (st->disposition & AV_DISPOSITION_DEFAULT);
  425. count = ffstream(st)->codec_info_nb_frames;
  426. bitrate = par->bit_rate;
  427. multiframe = FFMIN(5, count);
  428. if ((best_disposition > disposition) ||
  429. (best_disposition == disposition && best_multiframe > multiframe) ||
  430. (best_disposition == disposition && best_multiframe == multiframe && best_bitrate > bitrate) ||
  431. (best_disposition == disposition && best_multiframe == multiframe && best_bitrate == bitrate && best_count >= count))
  432. continue;
  433. best_disposition = disposition;
  434. best_count = count;
  435. best_bitrate = bitrate;
  436. best_multiframe = multiframe;
  437. ret = real_stream_index;
  438. best_decoder = decoder;
  439. if (program && i == nb_streams - 1 && ret < 0) {
  440. program = NULL;
  441. nb_streams = ic->nb_streams;
  442. /* no related stream found, try again with everything */
  443. i = 0;
  444. }
  445. }
  446. if (decoder_ret)
  447. *decoder_ret = best_decoder;
  448. return ret;
  449. }
  450. /**
  451. * Matches a stream specifier (but ignores requested index).
  452. *
  453. * @param indexptr set to point to the requested stream index if there is one
  454. *
  455. * @return <0 on error
  456. * 0 if st is NOT a matching stream
  457. * >0 if st is a matching stream
  458. */
  459. static int match_stream_specifier(const AVFormatContext *s, const AVStream *st,
  460. const char *spec, const char **indexptr,
  461. const AVStreamGroup **g, const AVProgram **p)
  462. {
  463. int match = 1; /* Stores if the specifier matches so far. */
  464. while (*spec) {
  465. if (*spec <= '9' && *spec >= '0') { /* opt:index */
  466. if (indexptr)
  467. *indexptr = spec;
  468. return match;
  469. } else if (*spec == 'v' || *spec == 'a' || *spec == 's' || *spec == 'd' ||
  470. *spec == 't' || *spec == 'V') { /* opt:[vasdtV] */
  471. enum AVMediaType type;
  472. int nopic = 0;
  473. switch (*spec++) {
  474. case 'v': type = AVMEDIA_TYPE_VIDEO; break;
  475. case 'a': type = AVMEDIA_TYPE_AUDIO; break;
  476. case 's': type = AVMEDIA_TYPE_SUBTITLE; break;
  477. case 'd': type = AVMEDIA_TYPE_DATA; break;
  478. case 't': type = AVMEDIA_TYPE_ATTACHMENT; break;
  479. case 'V': type = AVMEDIA_TYPE_VIDEO; nopic = 1; break;
  480. default: av_assert0(0);
  481. }
  482. if (*spec && *spec++ != ':') /* If we are not at the end, then another specifier must follow. */
  483. return AVERROR(EINVAL);
  484. if (type != st->codecpar->codec_type)
  485. match = 0;
  486. if (nopic && (st->disposition & AV_DISPOSITION_ATTACHED_PIC))
  487. match = 0;
  488. } else if (*spec == 'g' && *(spec + 1) == ':') {
  489. int64_t group_idx = -1, group_id = -1;
  490. int found = 0;
  491. char *endptr;
  492. spec += 2;
  493. if (*spec == '#' || (*spec == 'i' && *(spec + 1) == ':')) {
  494. spec += 1 + (*spec == 'i');
  495. group_id = strtol(spec, &endptr, 0);
  496. if (spec == endptr || (*endptr && *endptr++ != ':'))
  497. return AVERROR(EINVAL);
  498. spec = endptr;
  499. } else {
  500. group_idx = strtol(spec, &endptr, 0);
  501. /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
  502. if (spec == endptr || (*endptr && *endptr++ != ':'))
  503. return AVERROR(EINVAL);
  504. spec = endptr;
  505. }
  506. if (match) {
  507. if (group_id > 0) {
  508. for (unsigned i = 0; i < s->nb_stream_groups; i++) {
  509. if (group_id == s->stream_groups[i]->id) {
  510. group_idx = i;
  511. break;
  512. }
  513. }
  514. }
  515. if (group_idx < 0 || group_idx >= s->nb_stream_groups)
  516. return AVERROR(EINVAL);
  517. for (unsigned j = 0; j < s->stream_groups[group_idx]->nb_streams; j++) {
  518. if (st->index == s->stream_groups[group_idx]->streams[j]->index) {
  519. found = 1;
  520. if (g)
  521. *g = s->stream_groups[group_idx];
  522. break;
  523. }
  524. }
  525. }
  526. if (!found)
  527. match = 0;
  528. } else if (*spec == 'p' && *(spec + 1) == ':') {
  529. int prog_id;
  530. int found = 0;
  531. char *endptr;
  532. spec += 2;
  533. prog_id = strtol(spec, &endptr, 0);
  534. /* Disallow empty id and make sure that if we are not at the end, then another specifier must follow. */
  535. if (spec == endptr || (*endptr && *endptr++ != ':'))
  536. return AVERROR(EINVAL);
  537. spec = endptr;
  538. if (match) {
  539. for (unsigned i = 0; i < s->nb_programs; i++) {
  540. if (s->programs[i]->id != prog_id)
  541. continue;
  542. for (unsigned j = 0; j < s->programs[i]->nb_stream_indexes; j++) {
  543. if (st->index == s->programs[i]->stream_index[j]) {
  544. found = 1;
  545. if (p)
  546. *p = s->programs[i];
  547. i = s->nb_programs;
  548. break;
  549. }
  550. }
  551. }
  552. }
  553. if (!found)
  554. match = 0;
  555. } else if (*spec == '#' ||
  556. (*spec == 'i' && *(spec + 1) == ':')) {
  557. int stream_id;
  558. char *endptr;
  559. spec += 1 + (*spec == 'i');
  560. stream_id = strtol(spec, &endptr, 0);
  561. if (spec == endptr || *endptr) /* Disallow empty id and make sure we are at the end. */
  562. return AVERROR(EINVAL);
  563. return match && (stream_id == st->id);
  564. } else if (*spec == 'm' && *(spec + 1) == ':') {
  565. const AVDictionaryEntry *tag;
  566. char *key, *val;
  567. int ret;
  568. if (match) {
  569. spec += 2;
  570. val = strchr(spec, ':');
  571. key = val ? av_strndup(spec, val - spec) : av_strdup(spec);
  572. if (!key)
  573. return AVERROR(ENOMEM);
  574. tag = av_dict_get(st->metadata, key, NULL, 0);
  575. if (tag) {
  576. if (!val || !strcmp(tag->value, val + 1))
  577. ret = 1;
  578. else
  579. ret = 0;
  580. } else
  581. ret = 0;
  582. av_freep(&key);
  583. }
  584. return match && ret;
  585. } else if (*spec == 'u' && *(spec + 1) == '\0') {
  586. const AVCodecParameters *par = st->codecpar;
  587. int val;
  588. switch (par->codec_type) {
  589. case AVMEDIA_TYPE_AUDIO:
  590. val = par->sample_rate && par->ch_layout.nb_channels;
  591. if (par->format == AV_SAMPLE_FMT_NONE)
  592. return 0;
  593. break;
  594. case AVMEDIA_TYPE_VIDEO:
  595. val = par->width && par->height;
  596. if (par->format == AV_PIX_FMT_NONE)
  597. return 0;
  598. break;
  599. case AVMEDIA_TYPE_UNKNOWN:
  600. val = 0;
  601. break;
  602. default:
  603. val = 1;
  604. break;
  605. }
  606. return match && (par->codec_id != AV_CODEC_ID_NONE && val != 0);
  607. } else {
  608. return AVERROR(EINVAL);
  609. }
  610. }
  611. return match;
  612. }
  613. int avformat_match_stream_specifier(AVFormatContext *s, AVStream *st,
  614. const char *spec)
  615. {
  616. int ret, index;
  617. char *endptr;
  618. const char *indexptr = NULL;
  619. const AVStreamGroup *g = NULL;
  620. const AVProgram *p = NULL;
  621. int nb_streams;
  622. ret = match_stream_specifier(s, st, spec, &indexptr, &g, &p);
  623. if (ret < 0)
  624. goto error;
  625. if (!indexptr)
  626. return ret;
  627. index = strtol(indexptr, &endptr, 0);
  628. if (*endptr) { /* We can't have anything after the requested index. */
  629. ret = AVERROR(EINVAL);
  630. goto error;
  631. }
  632. /* This is not really needed but saves us a loop for simple stream index specifiers. */
  633. if (spec == indexptr)
  634. return (index == st->index);
  635. /* If we requested a matching stream index, we have to ensure st is that. */
  636. nb_streams = g ? g->nb_streams : (p ? p->nb_stream_indexes : s->nb_streams);
  637. for (int i = 0; i < nb_streams && index >= 0; i++) {
  638. unsigned idx = g ? g->streams[i]->index : (p ? p->stream_index[i] : i);
  639. const AVStream *candidate = s->streams[idx];
  640. ret = match_stream_specifier(s, candidate, spec, NULL, NULL, NULL);
  641. if (ret < 0)
  642. goto error;
  643. if (ret > 0 && index-- == 0 && st == candidate)
  644. return 1;
  645. }
  646. return 0;
  647. error:
  648. if (ret == AVERROR(EINVAL))
  649. av_log(s, AV_LOG_ERROR, "Invalid stream specifier: %s.\n", spec);
  650. return ret;
  651. }
  652. AVRational av_guess_sample_aspect_ratio(AVFormatContext *format, AVStream *stream, AVFrame *frame)
  653. {
  654. AVRational undef = {0, 1};
  655. AVRational stream_sample_aspect_ratio = stream ? stream->sample_aspect_ratio : undef;
  656. AVRational codec_sample_aspect_ratio = stream && stream->codecpar ? stream->codecpar->sample_aspect_ratio : undef;
  657. AVRational frame_sample_aspect_ratio = frame ? frame->sample_aspect_ratio : codec_sample_aspect_ratio;
  658. av_reduce(&stream_sample_aspect_ratio.num, &stream_sample_aspect_ratio.den,
  659. stream_sample_aspect_ratio.num, stream_sample_aspect_ratio.den, INT_MAX);
  660. if (stream_sample_aspect_ratio.num <= 0 || stream_sample_aspect_ratio.den <= 0)
  661. stream_sample_aspect_ratio = undef;
  662. av_reduce(&frame_sample_aspect_ratio.num, &frame_sample_aspect_ratio.den,
  663. frame_sample_aspect_ratio.num, frame_sample_aspect_ratio.den, INT_MAX);
  664. if (frame_sample_aspect_ratio.num <= 0 || frame_sample_aspect_ratio.den <= 0)
  665. frame_sample_aspect_ratio = undef;
  666. if (stream_sample_aspect_ratio.num)
  667. return stream_sample_aspect_ratio;
  668. else
  669. return frame_sample_aspect_ratio;
  670. }
  671. AVRational av_guess_frame_rate(AVFormatContext *format, AVStream *st, AVFrame *frame)
  672. {
  673. AVRational fr = st->r_frame_rate;
  674. const AVCodecDescriptor *desc = cffstream(st)->codec_desc;
  675. AVRational avg_fr = st->avg_frame_rate;
  676. if (avg_fr.num > 0 && avg_fr.den > 0 && fr.num > 0 && fr.den > 0 &&
  677. av_q2d(avg_fr) < 70 && av_q2d(fr) > 210) {
  678. fr = avg_fr;
  679. }
  680. if (desc && (desc->props & AV_CODEC_PROP_FIELDS)) {
  681. const AVCodecContext *const avctx = ffstream(st)->avctx;
  682. AVRational codec_fr = avctx->framerate;
  683. if ( codec_fr.num > 0 && codec_fr.den > 0 &&
  684. (fr.num == 0 || av_q2d(codec_fr) < av_q2d(fr)*0.7 && fabs(1.0 - av_q2d(av_div_q(avg_fr, fr))) > 0.1))
  685. fr = codec_fr;
  686. }
  687. return fr;
  688. }
  689. #if FF_API_INTERNAL_TIMING
  690. int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt,
  691. AVStream *ost, const AVStream *ist,
  692. enum AVTimebaseSource copy_tb)
  693. {
  694. const AVCodecDescriptor *desc = cffstream(ist)->codec_desc;
  695. const AVCodecContext *const dec_ctx = cffstream(ist)->avctx;
  696. AVRational mul = (AVRational){ desc && (desc->props & AV_CODEC_PROP_FIELDS) ? 2 : 1, 1 };
  697. AVRational dec_ctx_framerate = dec_ctx ? dec_ctx->framerate : (AVRational){ 0, 0 };
  698. AVRational dec_ctx_tb = dec_ctx_framerate.num ? av_inv_q(av_mul_q(dec_ctx_framerate, mul))
  699. : (ist->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? (AVRational){0, 1}
  700. : ist->time_base);
  701. AVRational enc_tb = ist->time_base;
  702. #if FF_API_TICKS_PER_FRAME
  703. FF_DISABLE_DEPRECATION_WARNINGS
  704. int ticks_per_frame = dec_ctx ? dec_ctx->ticks_per_frame : 1;
  705. FF_ENABLE_DEPRECATION_WARNINGS
  706. #endif
  707. /*
  708. * Avi is a special case here because it supports variable fps but
  709. * having the fps and timebase differe significantly adds quite some
  710. * overhead
  711. */
  712. if (!strcmp(ofmt->name, "avi")) {
  713. #if FF_API_R_FRAME_RATE
  714. if (copy_tb == AVFMT_TBCF_AUTO && ist->r_frame_rate.num
  715. && av_q2d(ist->r_frame_rate) >= av_q2d(ist->avg_frame_rate)
  716. && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(ist->time_base)
  717. && 0.5/av_q2d(ist->r_frame_rate) > av_q2d(dec_ctx_tb)
  718. && av_q2d(ist->time_base) < 1.0/500 && av_q2d(dec_ctx_tb) < 1.0/500
  719. || copy_tb == AVFMT_TBCF_R_FRAMERATE) {
  720. enc_tb.num = ist->r_frame_rate.den;
  721. enc_tb.den = 2*ist->r_frame_rate.num;
  722. } else
  723. #endif
  724. if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx_framerate.num &&
  725. av_q2d(av_inv_q(dec_ctx_framerate)) > 2*av_q2d(ist->time_base)
  726. && av_q2d(ist->time_base) < 1.0/500
  727. || (copy_tb == AVFMT_TBCF_DECODER &&
  728. (dec_ctx_framerate.num || ist->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))) {
  729. enc_tb = dec_ctx_tb;
  730. enc_tb.den *= 2;
  731. #if FF_API_TICKS_PER_FRAME
  732. enc_tb.num *= ticks_per_frame;
  733. #endif
  734. }
  735. } else if (!(ofmt->flags & AVFMT_VARIABLE_FPS)
  736. && !av_match_name(ofmt->name, "mov,mp4,3gp,3g2,psp,ipod,ismv,f4v")) {
  737. if (copy_tb == AVFMT_TBCF_AUTO && dec_ctx_framerate.num
  738. && av_q2d(av_inv_q(dec_ctx_framerate)) > av_q2d(ist->time_base)
  739. && av_q2d(ist->time_base) < 1.0/500
  740. || (copy_tb == AVFMT_TBCF_DECODER &&
  741. (dec_ctx_framerate.num || ist->codecpar->codec_type == AVMEDIA_TYPE_AUDIO))) {
  742. enc_tb = dec_ctx_tb;
  743. #if FF_API_TICKS_PER_FRAME
  744. enc_tb.num *= ticks_per_frame;
  745. #endif
  746. }
  747. }
  748. if (ost->codecpar->codec_tag == AV_RL32("tmcd")
  749. && dec_ctx_tb.num < dec_ctx_tb.den
  750. && dec_ctx_tb.num > 0
  751. && 121LL*dec_ctx_tb.num > dec_ctx_tb.den) {
  752. enc_tb = dec_ctx_tb;
  753. }
  754. av_reduce(&ffstream(ost)->transferred_mux_tb.num,
  755. &ffstream(ost)->transferred_mux_tb.den,
  756. enc_tb.num, enc_tb.den, INT_MAX);
  757. return 0;
  758. }
  759. AVRational av_stream_get_codec_timebase(const AVStream *st)
  760. {
  761. return cffstream(st)->avctx ? cffstream(st)->avctx->time_base : cffstream(st)->transferred_mux_tb;
  762. }
  763. #endif
  764. void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits,
  765. unsigned int pts_num, unsigned int pts_den)
  766. {
  767. FFStream *const sti = ffstream(st);
  768. AVRational new_tb;
  769. if (av_reduce(&new_tb.num, &new_tb.den, pts_num, pts_den, INT_MAX)) {
  770. if (new_tb.num != pts_num)
  771. av_log(NULL, AV_LOG_DEBUG,
  772. "st:%d removing common factor %d from timebase\n",
  773. st->index, pts_num / new_tb.num);
  774. } else
  775. av_log(NULL, AV_LOG_WARNING,
  776. "st:%d has too large timebase, reducing\n", st->index);
  777. if (new_tb.num <= 0 || new_tb.den <= 0) {
  778. av_log(NULL, AV_LOG_ERROR,
  779. "Ignoring attempt to set invalid timebase %d/%d for st:%d\n",
  780. new_tb.num, new_tb.den,
  781. st->index);
  782. return;
  783. }
  784. st->time_base = new_tb;
  785. if (sti->avctx)
  786. sti->avctx->pkt_timebase = new_tb;
  787. st->pts_wrap_bits = pts_wrap_bits;
  788. }
  789. const AVCodec *ff_find_decoder(AVFormatContext *s, const AVStream *st,
  790. enum AVCodecID codec_id)
  791. {
  792. switch (st->codecpar->codec_type) {
  793. case AVMEDIA_TYPE_VIDEO:
  794. if (s->video_codec) return s->video_codec;
  795. break;
  796. case AVMEDIA_TYPE_AUDIO:
  797. if (s->audio_codec) return s->audio_codec;
  798. break;
  799. case AVMEDIA_TYPE_SUBTITLE:
  800. if (s->subtitle_codec) return s->subtitle_codec;
  801. break;
  802. }
  803. return avcodec_find_decoder(codec_id);
  804. }
  805. int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src)
  806. {
  807. #define OFF(field) offsetof(AVFormatContext, field)
  808. static const unsigned offsets[] = {
  809. OFF(codec_whitelist), OFF(format_whitelist),
  810. OFF(protocol_whitelist), OFF(protocol_blacklist),
  811. };
  812. #undef OFF
  813. av_assert0(!dst->codec_whitelist &&
  814. !dst->format_whitelist &&
  815. !dst->protocol_whitelist &&
  816. !dst->protocol_blacklist);
  817. for (unsigned i = 0; i < FF_ARRAY_ELEMS(offsets); i++) {
  818. const char *src_str = *(char *const*)((const char*)src + offsets[i]);
  819. if (src_str) {
  820. char *dst_str = av_strdup(src_str);
  821. if (!dst_str) {
  822. av_log(dst, AV_LOG_ERROR, "Failed to duplicate black/whitelist\n");
  823. return AVERROR(ENOMEM);
  824. }
  825. *(char **)((char*)dst + offsets[i]) = dst_str;
  826. }
  827. }
  828. return 0;
  829. }
  830. int ff_is_intra_only(enum AVCodecID id)
  831. {
  832. const AVCodecDescriptor *d = avcodec_descriptor_get(id);
  833. if (!d)
  834. return 0;
  835. if ((d->type == AVMEDIA_TYPE_VIDEO || d->type == AVMEDIA_TYPE_AUDIO) &&
  836. !(d->props & AV_CODEC_PROP_INTRA_ONLY))
  837. return 0;
  838. return 1;
  839. }
  840. void ff_format_set_url(AVFormatContext *s, char *url)
  841. {
  842. av_assert0(url);
  843. av_freep(&s->url);
  844. s->url = url;
  845. }
  846. int ff_format_io_close(AVFormatContext *s, AVIOContext **pb)
  847. {
  848. int ret = 0;
  849. if (*pb)
  850. ret = s->io_close2(s, *pb);
  851. *pb = NULL;
  852. return ret;
  853. }