flvdec.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  1. /*
  2. * FLV demuxer
  3. * Copyright (c) 2003 The FFmpeg Project
  4. *
  5. * This demuxer will generate a 1 byte extradata for VP6F content.
  6. * It is composed of:
  7. * - upper 4 bits: difference between encoded width and visible width
  8. * - lower 4 bits: difference between encoded height and visible height
  9. *
  10. * This file is part of FFmpeg.
  11. *
  12. * FFmpeg is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * FFmpeg is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with FFmpeg; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/avstring.h"
  28. #include "libavutil/channel_layout.h"
  29. #include "libavutil/dict.h"
  30. #include "libavutil/dict_internal.h"
  31. #include "libavutil/mem.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/internal.h"
  34. #include "libavutil/intfloat.h"
  35. #include "libavutil/intreadwrite.h"
  36. #include "libavutil/mastering_display_metadata.h"
  37. #include "avformat.h"
  38. #include "demux.h"
  39. #include "internal.h"
  40. #include "flv.h"
  41. #define VALIDATE_INDEX_TS_THRESH 2500
  42. #define RESYNC_BUFFER_SIZE (1<<20)
  43. #define MAX_DEPTH 16 ///< arbitrary limit to prevent unbounded recursion
  44. typedef struct FLVMasteringMeta {
  45. double r_x;
  46. double r_y;
  47. double g_x;
  48. double g_y;
  49. double b_x;
  50. double b_y;
  51. double white_x;
  52. double white_y;
  53. double max_luminance;
  54. double min_luminance;
  55. } FLVMasteringMeta;
  56. typedef struct FLVMetaVideoColor {
  57. uint64_t matrix_coefficients;
  58. uint64_t transfer_characteristics;
  59. uint64_t primaries;
  60. uint64_t max_cll;
  61. uint64_t max_fall;
  62. FLVMasteringMeta mastering_meta;
  63. } FLVMetaVideoColor;
  64. enum FLVMetaColorInfoFlag {
  65. FLV_COLOR_INFO_FLAG_NONE = 0,
  66. FLV_COLOR_INFO_FLAG_GOT = 1,
  67. FLV_COLOR_INFO_FLAG_PARSING = 2,
  68. };
  69. typedef struct FLVContext {
  70. const AVClass *class; ///< Class for private options.
  71. int trust_metadata; ///< configure streams according onMetaData
  72. int trust_datasize; ///< trust data size of FLVTag
  73. int dump_full_metadata; ///< Dump full metadata of the onMetadata
  74. int wrong_dts; ///< wrong dts due to negative cts
  75. uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
  76. int new_extradata_size[FLV_STREAM_TYPE_NB];
  77. int last_sample_rate;
  78. int last_channels;
  79. struct {
  80. int64_t dts;
  81. int64_t pos;
  82. } validate_index[2];
  83. int validate_next;
  84. int validate_count;
  85. int searched_for_end;
  86. uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
  87. int broken_sizes;
  88. int64_t sum_flv_tag_size;
  89. int last_keyframe_stream_index;
  90. int keyframe_count;
  91. int64_t video_bit_rate;
  92. int64_t audio_bit_rate;
  93. int64_t *keyframe_times;
  94. int64_t *keyframe_filepositions;
  95. AVRational framerate;
  96. int64_t last_ts;
  97. int64_t time_offset;
  98. int64_t time_pos;
  99. FLVMetaVideoColor meta_color_info;
  100. enum FLVMetaColorInfoFlag meta_color_info_flag;
  101. uint8_t **mt_extradata;
  102. int *mt_extradata_sz;
  103. int mt_extradata_cnt;
  104. } FLVContext;
  105. /* AMF date type */
  106. typedef struct amf_date {
  107. double milliseconds;
  108. int16_t timezone;
  109. } amf_date;
  110. static int probe(const AVProbeData *p, int live)
  111. {
  112. const uint8_t *d = p->buf;
  113. unsigned offset = AV_RB32(d + 5);
  114. if (d[0] == 'F' &&
  115. d[1] == 'L' &&
  116. d[2] == 'V' &&
  117. d[3] < 5 && d[5] == 0 &&
  118. offset + 100 < p->buf_size &&
  119. offset > 8) {
  120. int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
  121. if (live == is_live)
  122. return AVPROBE_SCORE_MAX;
  123. }
  124. return 0;
  125. }
  126. static int flv_probe(const AVProbeData *p)
  127. {
  128. return probe(p, 0);
  129. }
  130. static int live_flv_probe(const AVProbeData *p)
  131. {
  132. return probe(p, 1);
  133. }
  134. static int kux_probe(const AVProbeData *p)
  135. {
  136. const uint8_t *d = p->buf;
  137. if (d[0] == 'K' &&
  138. d[1] == 'D' &&
  139. d[2] == 'K' &&
  140. d[3] == 0 &&
  141. d[4] == 0) {
  142. return AVPROBE_SCORE_EXTENSION + 1;
  143. }
  144. return 0;
  145. }
  146. static void add_keyframes_index(AVFormatContext *s)
  147. {
  148. FLVContext *flv = s->priv_data;
  149. AVStream *stream = NULL;
  150. unsigned int i = 0;
  151. if (flv->last_keyframe_stream_index < 0) {
  152. av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
  153. return;
  154. }
  155. av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
  156. stream = s->streams[flv->last_keyframe_stream_index];
  157. if (ffstream(stream)->nb_index_entries == 0) {
  158. for (i = 0; i < flv->keyframe_count; i++) {
  159. av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
  160. flv->keyframe_filepositions[i], flv->keyframe_times[i]);
  161. av_add_index_entry(stream, flv->keyframe_filepositions[i],
  162. flv->keyframe_times[i], 0, 0, AVINDEX_KEYFRAME);
  163. }
  164. } else
  165. av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
  166. if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  167. av_freep(&flv->keyframe_times);
  168. av_freep(&flv->keyframe_filepositions);
  169. flv->keyframe_count = 0;
  170. }
  171. }
  172. static AVStream *create_stream(AVFormatContext *s, int codec_type, int track_idx)
  173. {
  174. FFFormatContext *const si = ffformatcontext(s);
  175. FLVContext *flv = s->priv_data;
  176. AVStream *st = avformat_new_stream(s, NULL);
  177. if (!st)
  178. return NULL;
  179. st->codecpar->codec_type = codec_type;
  180. st->id = track_idx;
  181. avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  182. if (track_idx)
  183. return st;
  184. if (s->nb_streams>=3 ||( s->nb_streams==2
  185. && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
  186. && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
  187. && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_DATA
  188. && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_DATA))
  189. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  190. if (codec_type == AVMEDIA_TYPE_AUDIO) {
  191. st->codecpar->bit_rate = flv->audio_bit_rate;
  192. si->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
  193. }
  194. if (codec_type == AVMEDIA_TYPE_VIDEO) {
  195. st->codecpar->bit_rate = flv->video_bit_rate;
  196. si->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
  197. st->avg_frame_rate = flv->framerate;
  198. }
  199. flv->last_keyframe_stream_index = s->nb_streams - 1;
  200. add_keyframes_index(s);
  201. return st;
  202. }
  203. static int flv_same_audio_codec(AVCodecParameters *apar, int flags, uint32_t codec_fourcc)
  204. {
  205. int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  206. int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
  207. int codec_id;
  208. switch (codec_fourcc) {
  209. case MKBETAG('m', 'p', '4', 'a'):
  210. return apar->codec_id == AV_CODEC_ID_AAC;
  211. case MKBETAG('O', 'p', 'u', 's'):
  212. return apar->codec_id == AV_CODEC_ID_OPUS;
  213. case MKBETAG('.', 'm', 'p', '3'):
  214. return apar->codec_id == AV_CODEC_ID_MP3;
  215. case MKBETAG('f', 'L', 'a', 'C'):
  216. return apar->codec_id == AV_CODEC_ID_FLAC;
  217. case MKBETAG('a', 'c', '-', '3'):
  218. return apar->codec_id == AV_CODEC_ID_AC3;
  219. case MKBETAG('e', 'c', '-', '3'):
  220. return apar->codec_id == AV_CODEC_ID_EAC3;
  221. case 0:
  222. // Not enhanced flv, continue as normal.
  223. break;
  224. default:
  225. // Unknown FOURCC
  226. return 0;
  227. }
  228. if (!apar->codec_id && !apar->codec_tag)
  229. return 1;
  230. if (apar->bits_per_coded_sample != bits_per_coded_sample)
  231. return 0;
  232. switch (flv_codecid) {
  233. // no distinction between S16 and S8 PCM codec flags
  234. case FLV_CODECID_PCM:
  235. codec_id = bits_per_coded_sample == 8
  236. ? AV_CODEC_ID_PCM_U8
  237. #if HAVE_BIGENDIAN
  238. : AV_CODEC_ID_PCM_S16BE;
  239. #else
  240. : AV_CODEC_ID_PCM_S16LE;
  241. #endif
  242. return codec_id == apar->codec_id;
  243. case FLV_CODECID_PCM_LE:
  244. codec_id = bits_per_coded_sample == 8
  245. ? AV_CODEC_ID_PCM_U8
  246. : AV_CODEC_ID_PCM_S16LE;
  247. return codec_id == apar->codec_id;
  248. case FLV_CODECID_AAC:
  249. return apar->codec_id == AV_CODEC_ID_AAC;
  250. case FLV_CODECID_ADPCM:
  251. return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
  252. case FLV_CODECID_SPEEX:
  253. return apar->codec_id == AV_CODEC_ID_SPEEX;
  254. case FLV_CODECID_MP3:
  255. return apar->codec_id == AV_CODEC_ID_MP3;
  256. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  257. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  258. case FLV_CODECID_NELLYMOSER:
  259. return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
  260. case FLV_CODECID_PCM_MULAW:
  261. return apar->sample_rate == 8000 &&
  262. apar->codec_id == AV_CODEC_ID_PCM_MULAW;
  263. case FLV_CODECID_PCM_ALAW:
  264. return apar->sample_rate == 8000 &&
  265. apar->codec_id == AV_CODEC_ID_PCM_ALAW;
  266. default:
  267. return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  268. }
  269. }
  270. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
  271. AVCodecParameters *apar, int flv_codecid)
  272. {
  273. switch (flv_codecid) {
  274. // no distinction between S16 and S8 PCM codec flags
  275. case FLV_CODECID_PCM:
  276. apar->codec_id = apar->bits_per_coded_sample == 8
  277. ? AV_CODEC_ID_PCM_U8
  278. #if HAVE_BIGENDIAN
  279. : AV_CODEC_ID_PCM_S16BE;
  280. #else
  281. : AV_CODEC_ID_PCM_S16LE;
  282. #endif
  283. break;
  284. case FLV_CODECID_PCM_LE:
  285. apar->codec_id = apar->bits_per_coded_sample == 8
  286. ? AV_CODEC_ID_PCM_U8
  287. : AV_CODEC_ID_PCM_S16LE;
  288. break;
  289. case FLV_CODECID_AAC:
  290. apar->codec_id = AV_CODEC_ID_AAC;
  291. break;
  292. case FLV_CODECID_ADPCM:
  293. apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
  294. break;
  295. case FLV_CODECID_SPEEX:
  296. apar->codec_id = AV_CODEC_ID_SPEEX;
  297. apar->sample_rate = 16000;
  298. break;
  299. case FLV_CODECID_MP3:
  300. apar->codec_id = AV_CODEC_ID_MP3;
  301. ffstream(astream)->need_parsing = AVSTREAM_PARSE_FULL;
  302. break;
  303. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  304. // in case metadata does not otherwise declare samplerate
  305. apar->sample_rate = 8000;
  306. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  307. break;
  308. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  309. apar->sample_rate = 16000;
  310. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  311. break;
  312. case FLV_CODECID_NELLYMOSER:
  313. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  314. break;
  315. case FLV_CODECID_PCM_MULAW:
  316. apar->sample_rate = 8000;
  317. apar->codec_id = AV_CODEC_ID_PCM_MULAW;
  318. break;
  319. case FLV_CODECID_PCM_ALAW:
  320. apar->sample_rate = 8000;
  321. apar->codec_id = AV_CODEC_ID_PCM_ALAW;
  322. break;
  323. case MKBETAG('m', 'p', '4', 'a'):
  324. apar->codec_id = AV_CODEC_ID_AAC;
  325. return;
  326. case MKBETAG('O', 'p', 'u', 's'):
  327. apar->codec_id = AV_CODEC_ID_OPUS;
  328. apar->sample_rate = 48000;
  329. return;
  330. case MKBETAG('.', 'm', 'p', '3'):
  331. apar->codec_id = AV_CODEC_ID_MP3;
  332. return;
  333. case MKBETAG('f', 'L', 'a', 'C'):
  334. apar->codec_id = AV_CODEC_ID_FLAC;
  335. return;
  336. case MKBETAG('a', 'c', '-', '3'):
  337. apar->codec_id = AV_CODEC_ID_AC3;
  338. return;
  339. case MKBETAG('e', 'c', '-', '3'):
  340. apar->codec_id = AV_CODEC_ID_EAC3;
  341. return;
  342. default:
  343. avpriv_request_sample(s, "Audio codec (%x)",
  344. flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  345. apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  346. }
  347. }
  348. static int flv_same_video_codec(AVCodecParameters *vpar, uint32_t flv_codecid)
  349. {
  350. if (!vpar->codec_id && !vpar->codec_tag)
  351. return 1;
  352. switch (flv_codecid) {
  353. case FLV_CODECID_X_HEVC:
  354. case MKBETAG('h', 'v', 'c', '1'):
  355. return vpar->codec_id == AV_CODEC_ID_HEVC;
  356. case MKBETAG('a', 'v', '0', '1'):
  357. return vpar->codec_id == AV_CODEC_ID_AV1;
  358. case MKBETAG('v', 'p', '0', '9'):
  359. return vpar->codec_id == AV_CODEC_ID_VP9;
  360. case FLV_CODECID_H263:
  361. return vpar->codec_id == AV_CODEC_ID_FLV1;
  362. case FLV_CODECID_SCREEN:
  363. return vpar->codec_id == AV_CODEC_ID_FLASHSV;
  364. case FLV_CODECID_SCREEN2:
  365. return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
  366. case FLV_CODECID_VP6:
  367. return vpar->codec_id == AV_CODEC_ID_VP6F;
  368. case FLV_CODECID_VP6A:
  369. return vpar->codec_id == AV_CODEC_ID_VP6A;
  370. case FLV_CODECID_H264:
  371. case MKBETAG('a', 'v', 'c', '1'):
  372. return vpar->codec_id == AV_CODEC_ID_H264;
  373. default:
  374. return vpar->codec_tag == flv_codecid;
  375. }
  376. }
  377. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
  378. uint32_t flv_codecid, int read)
  379. {
  380. FFStream *const vstreami = ffstream(vstream);
  381. int ret = 0;
  382. AVCodecParameters *par = vstream->codecpar;
  383. enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
  384. switch (flv_codecid) {
  385. case FLV_CODECID_X_HEVC:
  386. case MKBETAG('h', 'v', 'c', '1'):
  387. par->codec_id = AV_CODEC_ID_HEVC;
  388. vstreami->need_parsing = AVSTREAM_PARSE_HEADERS;
  389. break;
  390. case MKBETAG('a', 'v', '0', '1'):
  391. par->codec_id = AV_CODEC_ID_AV1;
  392. vstreami->need_parsing = AVSTREAM_PARSE_HEADERS;
  393. break;
  394. case MKBETAG('v', 'p', '0', '9'):
  395. par->codec_id = AV_CODEC_ID_VP9;
  396. vstreami->need_parsing = AVSTREAM_PARSE_HEADERS;
  397. break;
  398. case FLV_CODECID_H263:
  399. par->codec_id = AV_CODEC_ID_FLV1;
  400. break;
  401. case FLV_CODECID_REALH263:
  402. par->codec_id = AV_CODEC_ID_H263;
  403. break; // Really mean it this time
  404. case FLV_CODECID_SCREEN:
  405. par->codec_id = AV_CODEC_ID_FLASHSV;
  406. break;
  407. case FLV_CODECID_SCREEN2:
  408. par->codec_id = AV_CODEC_ID_FLASHSV2;
  409. break;
  410. case FLV_CODECID_VP6:
  411. par->codec_id = AV_CODEC_ID_VP6F;
  412. case FLV_CODECID_VP6A:
  413. if (flv_codecid == FLV_CODECID_VP6A)
  414. par->codec_id = AV_CODEC_ID_VP6A;
  415. if (read) {
  416. if (par->extradata_size != 1) {
  417. ff_alloc_extradata(par, 1);
  418. }
  419. if (par->extradata)
  420. par->extradata[0] = avio_r8(s->pb);
  421. else
  422. avio_skip(s->pb, 1);
  423. }
  424. ret = 1; // 1 byte body size adjustment for flv_read_packet()
  425. break;
  426. case FLV_CODECID_H264:
  427. case MKBETAG('a', 'v', 'c', '1'):
  428. par->codec_id = AV_CODEC_ID_H264;
  429. vstreami->need_parsing = AVSTREAM_PARSE_HEADERS;
  430. break;
  431. case FLV_CODECID_MPEG4:
  432. par->codec_id = AV_CODEC_ID_MPEG4;
  433. break;
  434. default:
  435. avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
  436. par->codec_tag = flv_codecid;
  437. }
  438. if (!vstreami->need_context_update && par->codec_id != old_codec_id) {
  439. avpriv_request_sample(s, "Changing the codec id midstream");
  440. return AVERROR_PATCHWELCOME;
  441. }
  442. return ret;
  443. }
  444. static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
  445. {
  446. int ret;
  447. int length = avio_rb16(ioc);
  448. if (length >= buffsize) {
  449. avio_skip(ioc, length);
  450. return -1;
  451. }
  452. ret = avio_read(ioc, buffer, length);
  453. if (ret < 0)
  454. return ret;
  455. if (ret < length)
  456. return AVERROR_INVALIDDATA;
  457. buffer[length] = '\0';
  458. return length;
  459. }
  460. static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
  461. {
  462. FLVContext *flv = s->priv_data;
  463. unsigned int timeslen = 0, fileposlen = 0, i;
  464. char str_val[256];
  465. int64_t *times = NULL;
  466. int64_t *filepositions = NULL;
  467. int ret = AVERROR(ENOSYS);
  468. int64_t initial_pos = avio_tell(ioc);
  469. if (flv->keyframe_count > 0) {
  470. av_log(s, AV_LOG_DEBUG, "keyframes have been parsed\n");
  471. return 0;
  472. }
  473. av_assert0(!flv->keyframe_times);
  474. av_assert0(!flv->keyframe_filepositions);
  475. if (s->flags & AVFMT_FLAG_IGNIDX)
  476. return 0;
  477. while (avio_tell(ioc) < max_pos - 2 &&
  478. amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  479. int64_t **current_array;
  480. unsigned int arraylen;
  481. int factor;
  482. // Expect array object in context
  483. if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
  484. break;
  485. arraylen = avio_rb32(ioc);
  486. if (arraylen>>28)
  487. break;
  488. if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
  489. current_array = &times;
  490. timeslen = arraylen;
  491. factor = 1000;
  492. } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
  493. !filepositions) {
  494. current_array = &filepositions;
  495. fileposlen = arraylen;
  496. factor = 1;
  497. } else
  498. // unexpected metatag inside keyframes, will not use such
  499. // metadata for indexing
  500. break;
  501. if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
  502. ret = AVERROR(ENOMEM);
  503. goto finish;
  504. }
  505. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  506. double d;
  507. if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
  508. goto invalid;
  509. d = av_int2double(avio_rb64(ioc)) * factor;
  510. if (isnan(d) || d < INT64_MIN || d > INT64_MAX)
  511. goto invalid;
  512. if (avio_feof(ioc))
  513. goto invalid;
  514. current_array[0][i] = d;
  515. }
  516. if (times && filepositions) {
  517. // All done, exiting at a position allowing amf_parse_object
  518. // to finish parsing the object
  519. ret = 0;
  520. break;
  521. }
  522. }
  523. if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
  524. for (i = 0; i < FFMIN(2,fileposlen); i++) {
  525. flv->validate_index[i].pos = filepositions[i];
  526. flv->validate_index[i].dts = times[i];
  527. flv->validate_count = i + 1;
  528. }
  529. flv->keyframe_times = times;
  530. flv->keyframe_filepositions = filepositions;
  531. flv->keyframe_count = timeslen;
  532. times = NULL;
  533. filepositions = NULL;
  534. } else {
  535. invalid:
  536. av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
  537. }
  538. finish:
  539. av_freep(&times);
  540. av_freep(&filepositions);
  541. avio_seek(ioc, initial_pos, SEEK_SET);
  542. return ret;
  543. }
  544. static int amf_parse_object(AVFormatContext *s, AVStream *astream,
  545. AVStream *vstream, const char *key,
  546. int64_t max_pos, int depth)
  547. {
  548. AVCodecParameters *apar, *vpar;
  549. FLVContext *flv = s->priv_data;
  550. AVIOContext *ioc;
  551. AMFDataType amf_type;
  552. char str_val[1024];
  553. double num_val;
  554. amf_date date;
  555. if (depth > MAX_DEPTH)
  556. return AVERROR_PATCHWELCOME;
  557. num_val = 0;
  558. ioc = s->pb;
  559. if (avio_feof(ioc))
  560. return AVERROR_EOF;
  561. amf_type = avio_r8(ioc);
  562. switch (amf_type) {
  563. case AMF_DATA_TYPE_NUMBER:
  564. num_val = av_int2double(avio_rb64(ioc));
  565. break;
  566. case AMF_DATA_TYPE_BOOL:
  567. num_val = avio_r8(ioc);
  568. break;
  569. case AMF_DATA_TYPE_STRING:
  570. if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
  571. av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
  572. return -1;
  573. }
  574. break;
  575. case AMF_DATA_TYPE_OBJECT:
  576. if (key &&
  577. (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
  578. !strcmp(KEYFRAMES_TAG, key) && depth == 1)
  579. if (parse_keyframes_index(s, ioc, max_pos) < 0)
  580. av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
  581. else
  582. add_keyframes_index(s);
  583. while (avio_tell(ioc) < max_pos - 2 &&
  584. amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
  585. if (amf_parse_object(s, astream, vstream, str_val, max_pos,
  586. depth + 1) < 0)
  587. return -1; // if we couldn't skip, bomb out.
  588. if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
  589. av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
  590. return -1;
  591. }
  592. break;
  593. case AMF_DATA_TYPE_NULL:
  594. case AMF_DATA_TYPE_UNDEFINED:
  595. case AMF_DATA_TYPE_UNSUPPORTED:
  596. break; // these take up no additional space
  597. case AMF_DATA_TYPE_MIXEDARRAY:
  598. {
  599. unsigned v;
  600. avio_skip(ioc, 4); // skip 32-bit max array index
  601. while (avio_tell(ioc) < max_pos - 2 &&
  602. amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
  603. // this is the only case in which we would want a nested
  604. // parse to not skip over the object
  605. if (amf_parse_object(s, astream, vstream, str_val, max_pos,
  606. depth + 1) < 0)
  607. return -1;
  608. v = avio_r8(ioc);
  609. if (v != AMF_END_OF_OBJECT) {
  610. av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
  611. return -1;
  612. }
  613. break;
  614. }
  615. case AMF_DATA_TYPE_ARRAY:
  616. {
  617. unsigned int arraylen, i;
  618. arraylen = avio_rb32(ioc);
  619. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
  620. if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
  621. depth + 1) < 0)
  622. return -1; // if we couldn't skip, bomb out.
  623. }
  624. break;
  625. case AMF_DATA_TYPE_DATE:
  626. // timestamp (double) and UTC offset (int16)
  627. date.milliseconds = av_int2double(avio_rb64(ioc));
  628. date.timezone = avio_rb16(ioc);
  629. break;
  630. default: // unsupported type, we couldn't skip
  631. av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
  632. return -1;
  633. }
  634. if (key) {
  635. apar = astream ? astream->codecpar : NULL;
  636. vpar = vstream ? vstream->codecpar : NULL;
  637. // stream info doesn't live any deeper than the first object
  638. if (depth == 1) {
  639. if (amf_type == AMF_DATA_TYPE_NUMBER ||
  640. amf_type == AMF_DATA_TYPE_BOOL) {
  641. if (!strcmp(key, "duration"))
  642. s->duration = num_val * AV_TIME_BASE;
  643. else if (!strcmp(key, "videodatarate") &&
  644. 0 <= (int)(num_val * 1024.0))
  645. flv->video_bit_rate = num_val * 1024.0;
  646. else if (!strcmp(key, "audiodatarate") &&
  647. 0 <= (int)(num_val * 1024.0))
  648. flv->audio_bit_rate = num_val * 1024.0;
  649. else if (!strcmp(key, "framerate")) {
  650. flv->framerate = av_d2q(num_val, 1000);
  651. if (vstream)
  652. vstream->avg_frame_rate = flv->framerate;
  653. } else if (flv->trust_metadata) {
  654. if (!strcmp(key, "videocodecid") && vpar) {
  655. int ret = flv_set_video_codec(s, vstream, num_val, 0);
  656. if (ret < 0)
  657. return ret;
  658. } else if (!strcmp(key, "audiocodecid") && apar) {
  659. int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
  660. flv_set_audio_codec(s, astream, apar, id);
  661. } else if (!strcmp(key, "audiosamplerate") && apar) {
  662. apar->sample_rate = num_val;
  663. } else if (!strcmp(key, "audiosamplesize") && apar) {
  664. apar->bits_per_coded_sample = num_val;
  665. } else if (!strcmp(key, "stereo") && apar) {
  666. av_channel_layout_default(&apar->ch_layout, num_val + 1);
  667. } else if (!strcmp(key, "width") && vpar) {
  668. vpar->width = num_val;
  669. } else if (!strcmp(key, "height") && vpar) {
  670. vpar->height = num_val;
  671. } else if (!strcmp(key, "datastream")) {
  672. AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE, 0);
  673. if (!st)
  674. return AVERROR(ENOMEM);
  675. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  676. }
  677. }
  678. }
  679. if (amf_type == AMF_DATA_TYPE_STRING) {
  680. if (!strcmp(key, "encoder")) {
  681. int version = -1;
  682. if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
  683. if (version > 0 && version <= 655)
  684. flv->broken_sizes = 1;
  685. }
  686. } else if (!strcmp(key, "metadatacreator")) {
  687. if ( !strcmp (str_val, "MEGA")
  688. || !strncmp(str_val, "FlixEngine", 10))
  689. flv->broken_sizes = 1;
  690. }
  691. }
  692. }
  693. if (amf_type == AMF_DATA_TYPE_NUMBER && flv->meta_color_info_flag == FLV_COLOR_INFO_FLAG_PARSING) {
  694. FLVMetaVideoColor *meta_video_color = &flv->meta_color_info;
  695. if (!strcmp(key, "colorPrimaries")) {
  696. meta_video_color->primaries = num_val;
  697. } else if (!strcmp(key, "transferCharacteristics")) {
  698. meta_video_color->transfer_characteristics = num_val;
  699. } else if (!strcmp(key, "matrixCoefficients")) {
  700. meta_video_color->matrix_coefficients = num_val;
  701. } else if (!strcmp(key, "maxFall")) {
  702. meta_video_color->max_fall = num_val;
  703. } else if (!strcmp(key, "maxCLL")) {
  704. meta_video_color->max_cll = num_val;
  705. } else if (!strcmp(key, "redX")) {
  706. meta_video_color->mastering_meta.r_x = num_val;
  707. } else if (!strcmp(key, "redY")) {
  708. meta_video_color->mastering_meta.r_y = num_val;
  709. } else if (!strcmp(key, "greenX")) {
  710. meta_video_color->mastering_meta.g_x = num_val;
  711. } else if (!strcmp(key, "greenY")) {
  712. meta_video_color->mastering_meta.g_y = num_val;
  713. } else if (!strcmp(key, "blueX")) {
  714. meta_video_color->mastering_meta.b_x = num_val;
  715. } else if (!strcmp(key, "blueY")) {
  716. meta_video_color->mastering_meta.b_y = num_val;
  717. } else if (!strcmp(key, "whitePointX")) {
  718. meta_video_color->mastering_meta.white_x = num_val;
  719. } else if (!strcmp(key, "whitePointY")) {
  720. meta_video_color->mastering_meta.white_y = num_val;
  721. } else if (!strcmp(key, "maxLuminance")) {
  722. meta_video_color->mastering_meta.max_luminance = num_val;
  723. } else if (!strcmp(key, "minLuminance")) {
  724. meta_video_color->mastering_meta.min_luminance = num_val;
  725. }
  726. }
  727. if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
  728. ((!apar && !strcmp(key, "audiocodecid")) ||
  729. (!vpar && !strcmp(key, "videocodecid"))))
  730. s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
  731. if ((!strcmp(key, "duration") ||
  732. !strcmp(key, "filesize") ||
  733. !strcmp(key, "width") ||
  734. !strcmp(key, "height") ||
  735. !strcmp(key, "videodatarate") ||
  736. !strcmp(key, "framerate") ||
  737. !strcmp(key, "videocodecid") ||
  738. !strcmp(key, "audiodatarate") ||
  739. !strcmp(key, "audiosamplerate") ||
  740. !strcmp(key, "audiosamplesize") ||
  741. !strcmp(key, "stereo") ||
  742. !strcmp(key, "audiocodecid") ||
  743. !strcmp(key, "datastream")) && !flv->dump_full_metadata)
  744. return 0;
  745. s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  746. if (amf_type == AMF_DATA_TYPE_BOOL) {
  747. av_strlcpy(str_val, num_val > 0 ? "true" : "false",
  748. sizeof(str_val));
  749. av_dict_set(&s->metadata, key, str_val, 0);
  750. } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
  751. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  752. av_dict_set(&s->metadata, key, str_val, 0);
  753. } else if (amf_type == AMF_DATA_TYPE_STRING) {
  754. av_dict_set(&s->metadata, key, str_val, 0);
  755. } else if ( amf_type == AMF_DATA_TYPE_DATE
  756. && isfinite(date.milliseconds)
  757. && date.milliseconds > INT64_MIN/1000
  758. && date.milliseconds < INT64_MAX/1000
  759. ) {
  760. // timezone is ignored, since there is no easy way to offset the UTC
  761. // timestamp into the specified timezone
  762. avpriv_dict_set_timestamp(&s->metadata, key, 1000 * (int64_t)date.milliseconds);
  763. }
  764. }
  765. return 0;
  766. }
  767. #define TYPE_ONTEXTDATA 1
  768. #define TYPE_ONCAPTION 2
  769. #define TYPE_ONCAPTIONINFO 3
  770. #define TYPE_UNKNOWN 9
  771. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
  772. {
  773. FLVContext *flv = s->priv_data;
  774. AMFDataType type;
  775. AVStream *stream, *astream, *vstream;
  776. AVStream av_unused *dstream;
  777. AVIOContext *ioc;
  778. int i;
  779. char buffer[32];
  780. astream = NULL;
  781. vstream = NULL;
  782. dstream = NULL;
  783. ioc = s->pb;
  784. // first object needs to be "onMetaData" string
  785. type = avio_r8(ioc);
  786. if (type != AMF_DATA_TYPE_STRING ||
  787. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  788. return TYPE_UNKNOWN;
  789. if (!strcmp(buffer, "onTextData"))
  790. return TYPE_ONTEXTDATA;
  791. if (!strcmp(buffer, "onCaption"))
  792. return TYPE_ONCAPTION;
  793. if (!strcmp(buffer, "onCaptionInfo"))
  794. return TYPE_ONCAPTIONINFO;
  795. if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint") && strcmp(buffer, "|RtmpSampleAccess")) {
  796. av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
  797. return TYPE_UNKNOWN;
  798. }
  799. // find the streams now so that amf_parse_object doesn't need to do
  800. // the lookup every time it is called.
  801. for (i = 0; i < s->nb_streams; i++) {
  802. stream = s->streams[i];
  803. if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  804. vstream = stream;
  805. flv->last_keyframe_stream_index = i;
  806. } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  807. astream = stream;
  808. if (flv->last_keyframe_stream_index == -1)
  809. flv->last_keyframe_stream_index = i;
  810. } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  811. dstream = stream;
  812. }
  813. // parse the second object (we want a mixed array)
  814. if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  815. return -1;
  816. return 0;
  817. }
  818. static int flv_read_header(AVFormatContext *s)
  819. {
  820. FFFormatContext *const si = ffformatcontext(s);
  821. int flags;
  822. FLVContext *flv = s->priv_data;
  823. int offset;
  824. int pre_tag_size = 0;
  825. /* Actual FLV data at 0xe40000 in KUX file */
  826. if(!strcmp(s->iformat->name, "kux"))
  827. avio_skip(s->pb, 0xe40000);
  828. avio_skip(s->pb, 4);
  829. flags = avio_r8(s->pb);
  830. si->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
  831. s->ctx_flags |= AVFMTCTX_NOHEADER;
  832. offset = avio_rb32(s->pb);
  833. avio_seek(s->pb, offset, SEEK_SET);
  834. /* Annex E. The FLV File Format
  835. * E.3 TheFLVFileBody
  836. * Field Type Comment
  837. * PreviousTagSize0 UI32 Always 0
  838. * */
  839. pre_tag_size = avio_rb32(s->pb);
  840. if (pre_tag_size) {
  841. av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
  842. }
  843. s->start_time = 0;
  844. flv->sum_flv_tag_size = 0;
  845. flv->last_keyframe_stream_index = -1;
  846. return 0;
  847. }
  848. static int flv_read_close(AVFormatContext *s)
  849. {
  850. int i;
  851. FLVContext *flv = s->priv_data;
  852. for (i = 0; i < FLV_STREAM_TYPE_NB; i++)
  853. av_freep(&flv->new_extradata[i]);
  854. for (i = 0; i < flv->mt_extradata_cnt; i++)
  855. av_freep(&flv->mt_extradata[i]);
  856. av_freep(&flv->mt_extradata);
  857. av_freep(&flv->mt_extradata_sz);
  858. av_freep(&flv->keyframe_times);
  859. av_freep(&flv->keyframe_filepositions);
  860. return 0;
  861. }
  862. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  863. {
  864. int ret;
  865. if (!size)
  866. return 0;
  867. if ((ret = ff_get_extradata(s, st->codecpar, s->pb, size)) < 0)
  868. return ret;
  869. ffstream(st)->need_context_update = 1;
  870. return 0;
  871. }
  872. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  873. int size, int multitrack)
  874. {
  875. if (!size)
  876. return 0;
  877. if (!multitrack) {
  878. av_free(flv->new_extradata[stream]);
  879. flv->new_extradata[stream] = av_mallocz(size +
  880. AV_INPUT_BUFFER_PADDING_SIZE);
  881. if (!flv->new_extradata[stream])
  882. return AVERROR(ENOMEM);
  883. flv->new_extradata_size[stream] = size;
  884. avio_read(pb, flv->new_extradata[stream], size);
  885. } else {
  886. int new_count = stream + 1;
  887. if (flv->mt_extradata_cnt < new_count) {
  888. void *tmp = av_realloc_array(flv->mt_extradata, new_count,
  889. sizeof(*flv->mt_extradata));
  890. if (!tmp)
  891. return AVERROR(ENOMEM);
  892. flv->mt_extradata = tmp;
  893. tmp = av_realloc_array(flv->mt_extradata_sz, new_count,
  894. sizeof(*flv->mt_extradata_sz));
  895. if (!tmp)
  896. return AVERROR(ENOMEM);
  897. flv->mt_extradata_sz = tmp;
  898. // Set newly allocated pointers/sizes to 0
  899. for (int i = flv->mt_extradata_cnt; i < new_count; i++) {
  900. flv->mt_extradata[i] = NULL;
  901. flv->mt_extradata_sz[i] = 0;
  902. }
  903. flv->mt_extradata_cnt = new_count;
  904. }
  905. av_free(flv->mt_extradata[stream]);
  906. flv->mt_extradata[stream] = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  907. if (!flv->mt_extradata[stream])
  908. return AVERROR(ENOMEM);
  909. flv->mt_extradata_sz[stream] = size;
  910. avio_read(pb, flv->mt_extradata[stream], size);
  911. }
  912. return 0;
  913. }
  914. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  915. {
  916. av_log(s, AV_LOG_WARNING,
  917. "Found invalid index entries, clearing the index.\n");
  918. for (unsigned i = 0; i < s->nb_streams; i++) {
  919. FFStream *const sti = ffstream(s->streams[i]);
  920. int out = 0;
  921. /* Remove all index entries that point to >= pos */
  922. for (int j = 0; j < sti->nb_index_entries; j++)
  923. if (sti->index_entries[j].pos < pos)
  924. sti->index_entries[out++] = sti->index_entries[j];
  925. sti->nb_index_entries = out;
  926. }
  927. }
  928. static int amf_skip_tag(AVIOContext *pb, AMFDataType type, int depth)
  929. {
  930. int nb = -1, ret, parse_name = 1;
  931. if (depth > MAX_DEPTH)
  932. return AVERROR_PATCHWELCOME;
  933. if (avio_feof(pb))
  934. return AVERROR_EOF;
  935. switch (type) {
  936. case AMF_DATA_TYPE_NUMBER:
  937. avio_skip(pb, 8);
  938. break;
  939. case AMF_DATA_TYPE_BOOL:
  940. avio_skip(pb, 1);
  941. break;
  942. case AMF_DATA_TYPE_STRING:
  943. avio_skip(pb, avio_rb16(pb));
  944. break;
  945. case AMF_DATA_TYPE_ARRAY:
  946. parse_name = 0;
  947. case AMF_DATA_TYPE_MIXEDARRAY:
  948. nb = avio_rb32(pb);
  949. if (nb < 0)
  950. return AVERROR_INVALIDDATA;
  951. case AMF_DATA_TYPE_OBJECT:
  952. while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
  953. if (parse_name) {
  954. int size = avio_rb16(pb);
  955. if (!size) {
  956. avio_skip(pb, 1);
  957. break;
  958. }
  959. avio_skip(pb, size);
  960. }
  961. if ((ret = amf_skip_tag(pb, avio_r8(pb), depth + 1)) < 0)
  962. return ret;
  963. }
  964. break;
  965. case AMF_DATA_TYPE_NULL:
  966. case AMF_DATA_TYPE_OBJECT_END:
  967. break;
  968. default:
  969. return AVERROR_INVALIDDATA;
  970. }
  971. return 0;
  972. }
  973. static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
  974. int64_t dts, int64_t next)
  975. {
  976. AVIOContext *pb = s->pb;
  977. AVStream *st = NULL;
  978. char buf[20];
  979. int ret = AVERROR_INVALIDDATA;
  980. int i, length = -1;
  981. int array = 0;
  982. switch (avio_r8(pb)) {
  983. case AMF_DATA_TYPE_ARRAY:
  984. array = 1;
  985. case AMF_DATA_TYPE_MIXEDARRAY:
  986. avio_seek(pb, 4, SEEK_CUR);
  987. case AMF_DATA_TYPE_OBJECT:
  988. break;
  989. default:
  990. goto skip;
  991. }
  992. while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
  993. AMFDataType type = avio_r8(pb);
  994. if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
  995. length = avio_rb16(pb);
  996. ret = av_get_packet(pb, pkt, length);
  997. if (ret < 0)
  998. goto skip;
  999. else
  1000. break;
  1001. } else {
  1002. if ((ret = amf_skip_tag(pb, type, 0)) < 0)
  1003. goto skip;
  1004. }
  1005. }
  1006. if (length < 0) {
  1007. ret = AVERROR_INVALIDDATA;
  1008. goto skip;
  1009. }
  1010. for (i = 0; i < s->nb_streams; i++) {
  1011. st = s->streams[i];
  1012. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1013. break;
  1014. }
  1015. if (i == s->nb_streams) {
  1016. st = create_stream(s, AVMEDIA_TYPE_SUBTITLE, 0);
  1017. if (!st)
  1018. return AVERROR(ENOMEM);
  1019. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  1020. }
  1021. pkt->dts = dts;
  1022. pkt->pts = dts;
  1023. pkt->size = ret;
  1024. pkt->stream_index = st->index;
  1025. pkt->flags |= AV_PKT_FLAG_KEY;
  1026. skip:
  1027. avio_seek(s->pb, next + 4, SEEK_SET);
  1028. return ret;
  1029. }
  1030. static int resync(AVFormatContext *s)
  1031. {
  1032. FLVContext *flv = s->priv_data;
  1033. int64_t i;
  1034. int64_t pos = avio_tell(s->pb);
  1035. for (i=0; !avio_feof(s->pb); i++) {
  1036. int j = i & (RESYNC_BUFFER_SIZE-1);
  1037. int j1 = j + RESYNC_BUFFER_SIZE;
  1038. flv->resync_buffer[j ] =
  1039. flv->resync_buffer[j1] = avio_r8(s->pb);
  1040. if (i >= 8 && pos) {
  1041. uint8_t *d = flv->resync_buffer + j1 - 8;
  1042. if (d[0] == 'F' &&
  1043. d[1] == 'L' &&
  1044. d[2] == 'V' &&
  1045. d[3] < 5 && d[5] == 0) {
  1046. av_log(s, AV_LOG_WARNING, "Concatenated FLV detected, might fail to demux, decode and seek %"PRId64"\n", flv->last_ts);
  1047. flv->time_offset = flv->last_ts + 1;
  1048. flv->time_pos = avio_tell(s->pb);
  1049. }
  1050. }
  1051. if (i > 22) {
  1052. unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
  1053. if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
  1054. unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
  1055. unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
  1056. if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
  1057. unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
  1058. if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
  1059. avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
  1060. return 1;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. }
  1066. return AVERROR_EOF;
  1067. }
  1068. static int flv_parse_video_color_info(AVFormatContext *s, AVStream *st, int64_t next_pos)
  1069. {
  1070. int ret;
  1071. FLVContext *flv = s->priv_data;
  1072. AMFDataType type;
  1073. AVIOContext *ioc;
  1074. char buffer[32];
  1075. ioc = s->pb;
  1076. // first object needs to be "colorInfo" string
  1077. type = avio_r8(ioc);
  1078. if (type != AMF_DATA_TYPE_STRING ||
  1079. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  1080. return TYPE_UNKNOWN;
  1081. if (strcmp(buffer, "colorInfo")) {
  1082. av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
  1083. return TYPE_UNKNOWN;
  1084. }
  1085. flv->meta_color_info_flag = FLV_COLOR_INFO_FLAG_PARSING;
  1086. ret = amf_parse_object(s, NULL, NULL, buffer, next_pos, 0); // parse metadata
  1087. if (ret < 0) {
  1088. flv->meta_color_info_flag = FLV_COLOR_INFO_FLAG_NONE;
  1089. return ret;
  1090. }
  1091. flv->meta_color_info_flag = FLV_COLOR_INFO_FLAG_GOT;
  1092. return 0;
  1093. }
  1094. static int flv_update_video_color_info(AVFormatContext *s, AVStream *st)
  1095. {
  1096. FLVContext *flv = s->priv_data;
  1097. const FLVMetaVideoColor* meta_video_color = &flv->meta_color_info;
  1098. const FLVMasteringMeta *mastering_meta = &meta_video_color->mastering_meta;
  1099. int has_mastering_primaries, has_mastering_luminance;
  1100. // Mastering primaries are CIE 1931 coords, and must be > 0.
  1101. has_mastering_primaries =
  1102. mastering_meta->r_x > 0 && mastering_meta->r_y > 0 &&
  1103. mastering_meta->g_x > 0 && mastering_meta->g_y > 0 &&
  1104. mastering_meta->b_x > 0 && mastering_meta->b_y > 0 &&
  1105. mastering_meta->white_x > 0 && mastering_meta->white_y > 0;
  1106. has_mastering_luminance = mastering_meta->max_luminance > 0 && mastering_meta->min_luminance > 0;
  1107. if (meta_video_color->matrix_coefficients != AVCOL_SPC_RESERVED)
  1108. st->codecpar->color_space = meta_video_color->matrix_coefficients;
  1109. if (meta_video_color->primaries != AVCOL_PRI_RESERVED &&
  1110. meta_video_color->primaries != AVCOL_PRI_RESERVED0)
  1111. st->codecpar->color_primaries = meta_video_color->primaries;
  1112. if (meta_video_color->transfer_characteristics != AVCOL_TRC_RESERVED &&
  1113. meta_video_color->transfer_characteristics != AVCOL_TRC_RESERVED0)
  1114. st->codecpar->color_trc = meta_video_color->transfer_characteristics;
  1115. if (meta_video_color->max_cll && meta_video_color->max_fall) {
  1116. size_t size = 0;
  1117. AVContentLightMetadata *metadata = av_content_light_metadata_alloc(&size);
  1118. if (!metadata)
  1119. return AVERROR(ENOMEM);
  1120. if (!av_packet_side_data_add(&st->codecpar->coded_side_data, &st->codecpar->nb_coded_side_data,
  1121. AV_PKT_DATA_CONTENT_LIGHT_LEVEL, metadata, size, 0)) {
  1122. av_freep(&metadata);
  1123. return AVERROR(ENOMEM);
  1124. }
  1125. metadata->MaxCLL = meta_video_color->max_cll;
  1126. metadata->MaxFALL = meta_video_color->max_fall;
  1127. }
  1128. if (has_mastering_primaries || has_mastering_luminance) {
  1129. size_t size = 0;
  1130. AVMasteringDisplayMetadata *metadata = av_mastering_display_metadata_alloc_size(&size);
  1131. AVPacketSideData *sd;
  1132. if (!metadata)
  1133. return AVERROR(ENOMEM);
  1134. sd = av_packet_side_data_add(&st->codecpar->coded_side_data,
  1135. &st->codecpar->nb_coded_side_data,
  1136. AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
  1137. metadata, size, 0);
  1138. if (!sd) {
  1139. av_freep(&metadata);
  1140. return AVERROR(ENOMEM);
  1141. }
  1142. // hdrCll
  1143. if (has_mastering_luminance) {
  1144. metadata->max_luminance = av_d2q(mastering_meta->max_luminance, INT_MAX);
  1145. metadata->min_luminance = av_d2q(mastering_meta->min_luminance, INT_MAX);
  1146. metadata->has_luminance = 1;
  1147. }
  1148. // hdrMdcv
  1149. if (has_mastering_primaries) {
  1150. metadata->display_primaries[0][0] = av_d2q(mastering_meta->r_x, INT_MAX);
  1151. metadata->display_primaries[0][1] = av_d2q(mastering_meta->r_y, INT_MAX);
  1152. metadata->display_primaries[1][0] = av_d2q(mastering_meta->g_x, INT_MAX);
  1153. metadata->display_primaries[1][1] = av_d2q(mastering_meta->g_y, INT_MAX);
  1154. metadata->display_primaries[2][0] = av_d2q(mastering_meta->b_x, INT_MAX);
  1155. metadata->display_primaries[2][1] = av_d2q(mastering_meta->b_y, INT_MAX);
  1156. metadata->white_point[0] = av_d2q(mastering_meta->white_x, INT_MAX);
  1157. metadata->white_point[1] = av_d2q(mastering_meta->white_y, INT_MAX);
  1158. metadata->has_primaries = 1;
  1159. }
  1160. }
  1161. return 0;
  1162. }
  1163. static int flv_parse_mod_ex_data(AVFormatContext *s, int *pkt_type, int *size, int64_t *dts)
  1164. {
  1165. int ex_type, ret;
  1166. uint8_t *ex_data;
  1167. int ex_size = (uint8_t)avio_r8(s->pb) + 1;
  1168. *size -= 1;
  1169. if (ex_size == 256) {
  1170. ex_size = (uint16_t)avio_rb16(s->pb) + 1;
  1171. *size -= 2;
  1172. }
  1173. if (ex_size >= *size) {
  1174. av_log(s, AV_LOG_WARNING, "ModEx size larger than remaining data!\n");
  1175. return AVERROR(EINVAL);
  1176. }
  1177. ex_data = av_malloc(ex_size);
  1178. if (!ex_data)
  1179. return AVERROR(ENOMEM);
  1180. ret = avio_read(s->pb, ex_data, ex_size);
  1181. if (ret < 0) {
  1182. av_free(ex_data);
  1183. return ret;
  1184. }
  1185. *size -= ex_size;
  1186. ex_type = (uint8_t)avio_r8(s->pb);
  1187. *size -= 1;
  1188. *pkt_type = ex_type & 0x0f;
  1189. ex_type &= 0xf0;
  1190. if (ex_type == PacketModExTypeTimestampOffsetNano) {
  1191. uint32_t nano_offset;
  1192. if (ex_size != 3) {
  1193. av_log(s, AV_LOG_WARNING, "Invalid ModEx size for Type TimestampOffsetNano!\n");
  1194. nano_offset = 0;
  1195. } else {
  1196. nano_offset = (ex_data[0] << 16) | (ex_data[1] << 8) | ex_data[2];
  1197. }
  1198. // this is not likely to ever add anything, but right now timestamps are with ms precision
  1199. *dts += nano_offset / 1000000;
  1200. } else {
  1201. av_log(s, AV_LOG_INFO, "Unknown ModEx type: %d", ex_type);
  1202. }
  1203. av_free(ex_data);
  1204. return 0;
  1205. }
  1206. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  1207. {
  1208. FLVContext *flv = s->priv_data;
  1209. int ret = AVERROR_BUG, i, size, flags;
  1210. int res = 0;
  1211. enum FlvTagType type;
  1212. int stream_type = -1;
  1213. int64_t next, pos, meta_pos;
  1214. int64_t dts, pts = AV_NOPTS_VALUE;
  1215. int av_uninit(channels);
  1216. int av_uninit(sample_rate);
  1217. AVStream *st = NULL;
  1218. int last = -1;
  1219. int orig_size;
  1220. int enhanced_flv = 0;
  1221. int multitrack = 0;
  1222. int pkt_type = 0;
  1223. uint8_t track_idx = 0;
  1224. uint32_t codec_id = 0;
  1225. int multitrack_type = MultitrackTypeOneTrack;
  1226. retry:
  1227. /* pkt size is repeated at end. skip it */
  1228. pos = avio_tell(s->pb);
  1229. type = (avio_r8(s->pb) & 0x1F);
  1230. orig_size =
  1231. size = avio_rb24(s->pb);
  1232. flv->sum_flv_tag_size += size + 11LL;
  1233. dts = avio_rb24(s->pb);
  1234. dts |= (unsigned)avio_r8(s->pb) << 24;
  1235. av_log(s, AV_LOG_TRACE, "type:%d, size:%d, last:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, last, dts, avio_tell(s->pb));
  1236. if (avio_feof(s->pb))
  1237. return AVERROR_EOF;
  1238. avio_skip(s->pb, 3); /* stream id, always 0 */
  1239. flags = 0;
  1240. if (flv->validate_next < flv->validate_count) {
  1241. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  1242. if (pos == validate_pos) {
  1243. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  1244. VALIDATE_INDEX_TS_THRESH) {
  1245. flv->validate_next++;
  1246. } else {
  1247. clear_index_entries(s, validate_pos);
  1248. flv->validate_count = 0;
  1249. }
  1250. } else if (pos > validate_pos) {
  1251. clear_index_entries(s, validate_pos);
  1252. flv->validate_count = 0;
  1253. }
  1254. }
  1255. if (size == 0) {
  1256. ret = FFERROR_REDO;
  1257. goto leave;
  1258. }
  1259. next = size + avio_tell(s->pb);
  1260. if (type == FLV_TAG_TYPE_AUDIO) {
  1261. stream_type = FLV_STREAM_TYPE_AUDIO;
  1262. flags = avio_r8(s->pb);
  1263. size--;
  1264. if ((flags & FLV_AUDIO_CODECID_MASK) == FLV_CODECID_EX_HEADER) {
  1265. enhanced_flv = 1;
  1266. pkt_type = flags & ~FLV_AUDIO_CODECID_MASK;
  1267. while (pkt_type == PacketTypeModEx) {
  1268. ret = flv_parse_mod_ex_data(s, &pkt_type, &size, &dts);
  1269. if (ret < 0)
  1270. goto leave;
  1271. }
  1272. if (pkt_type == AudioPacketTypeMultitrack) {
  1273. uint8_t types = avio_r8(s->pb);
  1274. multitrack_type = types & 0xF0;
  1275. pkt_type = types & 0xF;
  1276. multitrack = 1;
  1277. size--;
  1278. }
  1279. codec_id = avio_rb32(s->pb);
  1280. size -= 4;
  1281. if (multitrack) {
  1282. track_idx = avio_r8(s->pb);
  1283. size--;
  1284. }
  1285. }
  1286. } else if (type == FLV_TAG_TYPE_VIDEO) {
  1287. stream_type = FLV_STREAM_TYPE_VIDEO;
  1288. flags = avio_r8(s->pb);
  1289. codec_id = flags & FLV_VIDEO_CODECID_MASK;
  1290. /*
  1291. * Reference Enhancing FLV 2023-03-v1.0.0-B.8
  1292. * https://github.com/veovera/enhanced-rtmp/blob/main/enhanced-rtmp-v1.pdf
  1293. * */
  1294. enhanced_flv = (flags >> 7) & 1;
  1295. pkt_type = enhanced_flv ? codec_id : 0;
  1296. size--;
  1297. while (pkt_type == PacketTypeModEx) {
  1298. ret = flv_parse_mod_ex_data(s, &pkt_type, &size, &dts);
  1299. if (ret < 0)
  1300. goto leave;
  1301. }
  1302. if (enhanced_flv && pkt_type != PacketTypeMetadata &&
  1303. (flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
  1304. goto skip;
  1305. if (pkt_type == PacketTypeMultitrack) {
  1306. uint8_t types = avio_r8(s->pb);
  1307. multitrack_type = types & 0xF0;
  1308. pkt_type = types & 0xF;
  1309. multitrack = 1;
  1310. size--;
  1311. }
  1312. if (enhanced_flv) {
  1313. codec_id = avio_rb32(s->pb);
  1314. size -= 4;
  1315. }
  1316. if (multitrack) {
  1317. track_idx = avio_r8(s->pb);
  1318. size--;
  1319. }
  1320. if (enhanced_flv && (flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD) {
  1321. if (pkt_type == PacketTypeMetadata) {
  1322. int sret = flv_parse_video_color_info(s, st, next);
  1323. av_log(s, AV_LOG_DEBUG, "enhanced flv parse metadata ret %d and skip\n", sret);
  1324. }
  1325. goto skip;
  1326. } else if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD) {
  1327. goto skip;
  1328. }
  1329. } else if (type == FLV_TAG_TYPE_META) {
  1330. stream_type=FLV_STREAM_TYPE_SUBTITLE;
  1331. if (size > 13 + 1 + 4) { // Header-type metadata stuff
  1332. int type;
  1333. meta_pos = avio_tell(s->pb);
  1334. type = flv_read_metabody(s, next);
  1335. if (type == 0 && dts == 0 || type < 0) {
  1336. if (type < 0 && flv->validate_count &&
  1337. flv->validate_index[0].pos > next &&
  1338. flv->validate_index[0].pos - 4 < next) {
  1339. av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
  1340. next = flv->validate_index[0].pos - 4;
  1341. }
  1342. goto skip;
  1343. } else if (type == TYPE_ONTEXTDATA) {
  1344. avpriv_request_sample(s, "OnTextData packet");
  1345. return flv_data_packet(s, pkt, dts, next);
  1346. } else if (type == TYPE_ONCAPTION) {
  1347. return flv_data_packet(s, pkt, dts, next);
  1348. } else if (type == TYPE_UNKNOWN) {
  1349. stream_type = FLV_STREAM_TYPE_DATA;
  1350. }
  1351. avio_seek(s->pb, meta_pos, SEEK_SET);
  1352. }
  1353. } else {
  1354. av_log(s, AV_LOG_DEBUG,
  1355. "Skipping flv packet: type %d, size %d, flags %d.\n",
  1356. type, size, flags);
  1357. skip:
  1358. if (avio_seek(s->pb, next, SEEK_SET) != next) {
  1359. // This can happen if flv_read_metabody above read past
  1360. // next, on a non-seekable input, and the preceding data has
  1361. // been flushed out from the IO buffer.
  1362. av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
  1363. return AVERROR_INVALIDDATA;
  1364. }
  1365. ret = FFERROR_REDO;
  1366. goto leave;
  1367. }
  1368. /* skip empty data packets */
  1369. if (!size) {
  1370. ret = FFERROR_REDO;
  1371. goto leave;
  1372. }
  1373. for (;;) {
  1374. int track_size = size;
  1375. if (multitrack_type != MultitrackTypeOneTrack) {
  1376. track_size = avio_rb24(s->pb);
  1377. size -= 3;
  1378. }
  1379. /* now find stream */
  1380. for (i = 0; i < s->nb_streams; i++) {
  1381. st = s->streams[i];
  1382. if (stream_type == FLV_STREAM_TYPE_AUDIO) {
  1383. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  1384. (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags, codec_id)) &&
  1385. st->id == track_idx)
  1386. break;
  1387. } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
  1388. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  1389. (s->video_codec_id || flv_same_video_codec(st->codecpar, codec_id)) &&
  1390. st->id == track_idx)
  1391. break;
  1392. } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
  1393. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1394. break;
  1395. } else if (stream_type == FLV_STREAM_TYPE_DATA) {
  1396. if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
  1397. break;
  1398. }
  1399. }
  1400. if (i == s->nb_streams) {
  1401. static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA};
  1402. st = create_stream(s, stream_types[stream_type], track_idx);
  1403. if (!st)
  1404. return AVERROR(ENOMEM);
  1405. }
  1406. av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
  1407. if (flv->time_pos <= pos) {
  1408. dts += flv->time_offset;
  1409. }
  1410. if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  1411. ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
  1412. stream_type == FLV_STREAM_TYPE_AUDIO))
  1413. av_add_index_entry(st, pos, dts, track_size, 0, AVINDEX_KEYFRAME);
  1414. if ((st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)) ||
  1415. (st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && stream_type == FLV_STREAM_TYPE_VIDEO)) ||
  1416. st->discard >= AVDISCARD_ALL) {
  1417. avio_seek(s->pb, next, SEEK_SET);
  1418. ret = FFERROR_REDO;
  1419. goto leave;
  1420. }
  1421. // if not streamed and no duration from metadata then seek to end to find
  1422. // the duration from the timestamps
  1423. if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  1424. (!s->duration || s->duration == AV_NOPTS_VALUE) &&
  1425. !flv->searched_for_end) {
  1426. int final_size;
  1427. const int64_t pos = avio_tell(s->pb);
  1428. // Read the last 4 bytes of the file, this should be the size of the
  1429. // previous FLV tag. Use the timestamp of its payload as duration.
  1430. int64_t fsize = avio_size(s->pb);
  1431. retry_duration:
  1432. avio_seek(s->pb, fsize - 4, SEEK_SET);
  1433. final_size = avio_rb32(s->pb);
  1434. if (final_size > 0 && final_size < fsize) {
  1435. // Seek to the start of the last FLV tag at position (fsize - 4 - final_size)
  1436. // but skip the byte indicating the type.
  1437. avio_seek(s->pb, fsize - 3 - final_size, SEEK_SET);
  1438. if (final_size == avio_rb24(s->pb) + 11) {
  1439. uint32_t ts = avio_rb24(s->pb);
  1440. ts |= (unsigned)avio_r8(s->pb) << 24;
  1441. if (ts)
  1442. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  1443. else if (fsize >= 8 && fsize - 8 >= final_size) {
  1444. fsize -= final_size+4;
  1445. goto retry_duration;
  1446. }
  1447. }
  1448. }
  1449. avio_seek(s->pb, pos, SEEK_SET);
  1450. flv->searched_for_end = 1;
  1451. }
  1452. if (stream_type == FLV_STREAM_TYPE_AUDIO && !enhanced_flv) {
  1453. int bits_per_coded_sample;
  1454. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  1455. sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
  1456. FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
  1457. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  1458. if (!av_channel_layout_check(&st->codecpar->ch_layout) ||
  1459. !st->codecpar->sample_rate ||
  1460. !st->codecpar->bits_per_coded_sample) {
  1461. av_channel_layout_default(&st->codecpar->ch_layout, channels);
  1462. st->codecpar->sample_rate = sample_rate;
  1463. st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
  1464. }
  1465. if (!st->codecpar->codec_id) {
  1466. flv_set_audio_codec(s, st, st->codecpar,
  1467. flags & FLV_AUDIO_CODECID_MASK);
  1468. flv->last_sample_rate =
  1469. sample_rate = st->codecpar->sample_rate;
  1470. flv->last_channels =
  1471. channels = st->codecpar->ch_layout.nb_channels;
  1472. } else {
  1473. AVCodecParameters *par = avcodec_parameters_alloc();
  1474. if (!par) {
  1475. ret = AVERROR(ENOMEM);
  1476. goto leave;
  1477. }
  1478. par->sample_rate = sample_rate;
  1479. par->bits_per_coded_sample = bits_per_coded_sample;
  1480. flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
  1481. sample_rate = par->sample_rate;
  1482. avcodec_parameters_free(&par);
  1483. }
  1484. } else if (stream_type == FLV_STREAM_TYPE_AUDIO) {
  1485. if (!st->codecpar->codec_id)
  1486. flv_set_audio_codec(s, st, st->codecpar,
  1487. codec_id ? codec_id : (flags & FLV_AUDIO_CODECID_MASK));
  1488. // These are not signalled in the flags anymore
  1489. channels = 0;
  1490. sample_rate = 0;
  1491. if (pkt_type == AudioPacketTypeMultichannelConfig) {
  1492. int channel_order = avio_r8(s->pb);
  1493. channels = avio_r8(s->pb);
  1494. size -= 2;
  1495. track_size -= 2;
  1496. av_channel_layout_uninit(&st->codecpar->ch_layout);
  1497. if (channel_order == AudioChannelOrderCustom) {
  1498. ret = av_channel_layout_custom_init(&st->codecpar->ch_layout, channels);
  1499. if (ret < 0)
  1500. return ret;
  1501. for (i = 0; i < channels; i++) {
  1502. uint8_t id = avio_r8(s->pb);
  1503. size--;
  1504. track_size--;
  1505. if (id < 18)
  1506. st->codecpar->ch_layout.u.map[i].id = id;
  1507. else if (id >= 18 && id <= 23)
  1508. st->codecpar->ch_layout.u.map[i].id = id - 18 + AV_CHAN_LOW_FREQUENCY_2;
  1509. else if (id == 0xFE)
  1510. st->codecpar->ch_layout.u.map[i].id = AV_CHAN_UNUSED;
  1511. else
  1512. st->codecpar->ch_layout.u.map[i].id = AV_CHAN_UNKNOWN;
  1513. }
  1514. } else if (channel_order == AudioChannelOrderNative) {
  1515. uint64_t mask = avio_rb32(s->pb);
  1516. size -= 4;
  1517. track_size -= 4;
  1518. // The first 18 entries in the mask match ours, but the remaining 6 entries start at AV_CHAN_LOW_FREQUENCY_2
  1519. mask = (mask & 0x3FFFF) | ((mask & 0xFC0000) << (AV_CHAN_LOW_FREQUENCY_2 - 18));
  1520. ret = av_channel_layout_from_mask(&st->codecpar->ch_layout, mask);
  1521. if (ret < 0)
  1522. return ret;
  1523. } else {
  1524. av_channel_layout_default(&st->codecpar->ch_layout, channels);
  1525. }
  1526. av_log(s, AV_LOG_DEBUG, "Set channel data from MultiChannel info.\n");
  1527. goto next_track;
  1528. }
  1529. } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
  1530. int sret = flv_set_video_codec(s, st, codec_id, 1);
  1531. if (sret < 0)
  1532. return sret;
  1533. size -= sret;
  1534. track_size -= sret;
  1535. } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
  1536. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  1537. } else if (stream_type == FLV_STREAM_TYPE_DATA) {
  1538. st->codecpar->codec_id = AV_CODEC_ID_NONE; // Opaque AMF data
  1539. }
  1540. if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
  1541. st->codecpar->codec_id == AV_CODEC_ID_OPUS ||
  1542. st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
  1543. st->codecpar->codec_id == AV_CODEC_ID_H264 ||
  1544. st->codecpar->codec_id == AV_CODEC_ID_MPEG4 ||
  1545. st->codecpar->codec_id == AV_CODEC_ID_HEVC ||
  1546. st->codecpar->codec_id == AV_CODEC_ID_AV1 ||
  1547. st->codecpar->codec_id == AV_CODEC_ID_VP9) {
  1548. int type = 0;
  1549. if (enhanced_flv) {
  1550. type = pkt_type;
  1551. } else {
  1552. type = avio_r8(s->pb);
  1553. size--;
  1554. track_size--;
  1555. }
  1556. if (size < 0 || track_size < 0) {
  1557. ret = AVERROR_INVALIDDATA;
  1558. goto leave;
  1559. }
  1560. if (enhanced_flv && stream_type == FLV_STREAM_TYPE_VIDEO &&
  1561. flv->meta_color_info_flag == FLV_COLOR_INFO_FLAG_GOT) {
  1562. flv_update_video_color_info(s, st); // update av packet side data
  1563. flv->meta_color_info_flag = FLV_COLOR_INFO_FLAG_NONE;
  1564. }
  1565. if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4 ||
  1566. ((st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_HEVC) &&
  1567. (!enhanced_flv || type == PacketTypeCodedFrames))) {
  1568. // sign extension
  1569. int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
  1570. pts = av_sat_add64(dts, cts);
  1571. if (cts < 0) { // dts might be wrong
  1572. if (!flv->wrong_dts)
  1573. av_log(s, AV_LOG_WARNING,
  1574. "Negative cts, previous timestamps might be wrong.\n");
  1575. flv->wrong_dts = 1;
  1576. } else if (FFABS(dts - pts) > 1000*60*15) {
  1577. av_log(s, AV_LOG_WARNING,
  1578. "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
  1579. dts = pts = AV_NOPTS_VALUE;
  1580. }
  1581. size -= 3;
  1582. track_size -= 3;
  1583. }
  1584. if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
  1585. st->codecpar->codec_id == AV_CODEC_ID_OPUS || st->codecpar->codec_id == AV_CODEC_ID_FLAC ||
  1586. st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_HEVC ||
  1587. st->codecpar->codec_id == AV_CODEC_ID_AV1 || st->codecpar->codec_id == AV_CODEC_ID_VP9)) {
  1588. AVDictionaryEntry *t;
  1589. if (st->codecpar->extradata) {
  1590. if ((ret = flv_queue_extradata(flv, s->pb, multitrack ? track_idx : stream_type, track_size, multitrack)) < 0)
  1591. return ret;
  1592. ret = FFERROR_REDO;
  1593. goto leave;
  1594. }
  1595. if ((ret = flv_get_extradata(s, st, track_size)) < 0)
  1596. return ret;
  1597. /* Workaround for buggy Omnia A/XE encoder */
  1598. t = av_dict_get(s->metadata, "Encoder", NULL, 0);
  1599. if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
  1600. st->codecpar->extradata_size = 2;
  1601. ret = FFERROR_REDO;
  1602. goto leave;
  1603. }
  1604. }
  1605. /* skip empty or broken data packets */
  1606. if (size <= 0 || track_size < 0) {
  1607. ret = FFERROR_REDO;
  1608. goto leave;
  1609. }
  1610. /* skip empty data track */
  1611. if (!track_size)
  1612. goto next_track;
  1613. ret = av_get_packet(s->pb, pkt, track_size);
  1614. if (ret < 0)
  1615. return ret;
  1616. track_size -= ret;
  1617. size -= ret;
  1618. pkt->dts = dts;
  1619. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  1620. pkt->stream_index = st->index;
  1621. pkt->pos = pos;
  1622. if (!multitrack && flv->new_extradata[stream_type]) {
  1623. ret = av_packet_add_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  1624. flv->new_extradata[stream_type],
  1625. flv->new_extradata_size[stream_type]);
  1626. if (ret < 0)
  1627. return ret;
  1628. flv->new_extradata[stream_type] = NULL;
  1629. flv->new_extradata_size[stream_type] = 0;
  1630. } else if (multitrack &&
  1631. flv->mt_extradata_cnt > track_idx &&
  1632. flv->mt_extradata[track_idx]) {
  1633. ret = av_packet_add_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  1634. flv->mt_extradata[track_idx],
  1635. flv->mt_extradata_sz[track_idx]);
  1636. if (ret < 0)
  1637. return ret;
  1638. flv->mt_extradata[track_idx] = NULL;
  1639. flv->mt_extradata_sz[track_idx] = 0;
  1640. }
  1641. if (stream_type == FLV_STREAM_TYPE_AUDIO && !enhanced_flv &&
  1642. (sample_rate != flv->last_sample_rate ||
  1643. channels != flv->last_channels)) {
  1644. flv->last_sample_rate = sample_rate;
  1645. flv->last_channels = channels;
  1646. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  1647. }
  1648. if (stream_type == FLV_STREAM_TYPE_AUDIO ||
  1649. (flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
  1650. stream_type == FLV_STREAM_TYPE_SUBTITLE ||
  1651. stream_type == FLV_STREAM_TYPE_DATA)
  1652. pkt->flags |= AV_PKT_FLAG_KEY;
  1653. ret = ff_buffer_packet(s, pkt);
  1654. if (ret < 0)
  1655. return ret;
  1656. res = FFERROR_REDO;
  1657. next_track:
  1658. if (track_size) {
  1659. av_log(s, AV_LOG_WARNING, "Track size mismatch: %d!\n", track_size);
  1660. avio_skip(s->pb, track_size);
  1661. size -= track_size;
  1662. }
  1663. if (!size)
  1664. break;
  1665. if (multitrack_type == MultitrackTypeOneTrack) {
  1666. av_log(s, AV_LOG_ERROR, "Attempted to read next track in single-track mode.\n");
  1667. ret = FFERROR_REDO;
  1668. goto leave;
  1669. }
  1670. if (multitrack_type == MultitrackTypeManyTracksManyCodecs) {
  1671. codec_id = avio_rb32(s->pb);
  1672. size -= 4;
  1673. }
  1674. track_idx = avio_r8(s->pb);
  1675. size--;
  1676. if (avio_feof(s->pb)) {
  1677. av_log(s, AV_LOG_WARNING, "Premature EOF\n");
  1678. /* return REDO so that any potentially queued up packages can be drained first */
  1679. return FFERROR_REDO;
  1680. }
  1681. }
  1682. ret = 0;
  1683. leave:
  1684. last = avio_rb32(s->pb);
  1685. if (!flv->trust_datasize) {
  1686. if (last != orig_size + 11 && last != orig_size + 10 &&
  1687. !avio_feof(s->pb) &&
  1688. (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
  1689. !flv->broken_sizes) {
  1690. av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %"PRId64"\n", last, orig_size + 11, flv->sum_flv_tag_size);
  1691. avio_seek(s->pb, pos + 1, SEEK_SET);
  1692. ret = resync(s);
  1693. av_packet_unref(pkt);
  1694. if (ret >= 0) {
  1695. goto retry;
  1696. }
  1697. }
  1698. }
  1699. if (ret >= 0)
  1700. flv->last_ts = pkt->dts;
  1701. return ret ? ret : res;
  1702. }
  1703. static int flv_read_seek(AVFormatContext *s, int stream_index,
  1704. int64_t ts, int flags)
  1705. {
  1706. FLVContext *flv = s->priv_data;
  1707. flv->validate_count = 0;
  1708. return avio_seek_time(s->pb, stream_index, ts, flags);
  1709. }
  1710. #define OFFSET(x) offsetof(FLVContext, x)
  1711. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1712. static const AVOption options[] = {
  1713. { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1714. { "flv_full_metadata", "Dump full metadata of the onMetadata", OFFSET(dump_full_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1715. { "flv_ignore_prevtag", "Ignore the Size of previous tag", OFFSET(trust_datasize), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1716. { NULL }
  1717. };
  1718. static const AVClass flv_kux_class = {
  1719. .class_name = "(live) flv/kux demuxer",
  1720. .item_name = av_default_item_name,
  1721. .option = options,
  1722. .version = LIBAVUTIL_VERSION_INT,
  1723. };
  1724. const FFInputFormat ff_flv_demuxer = {
  1725. .p.name = "flv",
  1726. .p.long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
  1727. .p.extensions = "flv",
  1728. .p.priv_class = &flv_kux_class,
  1729. .priv_data_size = sizeof(FLVContext),
  1730. .read_probe = flv_probe,
  1731. .read_header = flv_read_header,
  1732. .read_packet = flv_read_packet,
  1733. .read_seek = flv_read_seek,
  1734. .read_close = flv_read_close,
  1735. };
  1736. const FFInputFormat ff_live_flv_demuxer = {
  1737. .p.name = "live_flv",
  1738. .p.long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
  1739. .p.extensions = "flv",
  1740. .p.priv_class = &flv_kux_class,
  1741. .p.flags = AVFMT_TS_DISCONT,
  1742. .priv_data_size = sizeof(FLVContext),
  1743. .read_probe = live_flv_probe,
  1744. .read_header = flv_read_header,
  1745. .read_packet = flv_read_packet,
  1746. .read_seek = flv_read_seek,
  1747. .read_close = flv_read_close,
  1748. };
  1749. const FFInputFormat ff_kux_demuxer = {
  1750. .p.name = "kux",
  1751. .p.long_name = NULL_IF_CONFIG_SMALL("KUX (YouKu)"),
  1752. .p.extensions = "kux",
  1753. .p.priv_class = &flv_kux_class,
  1754. .priv_data_size = sizeof(FLVContext),
  1755. .read_probe = kux_probe,
  1756. .read_header = flv_read_header,
  1757. .read_packet = flv_read_packet,
  1758. .read_seek = flv_read_seek,
  1759. .read_close = flv_read_close,
  1760. };