nutenc.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. /*
  2. * nut muxer
  3. * Copyright (c) 2004-2007 Michael Niedermayer
  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 "libavutil/intreadwrite.h"
  22. #include "libavutil/mathematics.h"
  23. #include "libavutil/tree.h"
  24. #include "libavutil/dict.h"
  25. #include "libavutil/avassert.h"
  26. #include "libavcodec/mpegaudiodata.h"
  27. #include "nut.h"
  28. #include "internal.h"
  29. #include "avio_internal.h"
  30. static int find_expected_header(AVCodecContext *c, int size, int key_frame, uint8_t out[64]){
  31. int sample_rate= c->sample_rate;
  32. if(size>4096)
  33. return 0;
  34. AV_WB24(out, 1);
  35. if(c->codec_id == AV_CODEC_ID_MPEG4){
  36. if(key_frame){
  37. return 3;
  38. }else{
  39. out[3]= 0xB6;
  40. return 4;
  41. }
  42. }else if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO || c->codec_id == AV_CODEC_ID_MPEG2VIDEO){
  43. return 3;
  44. }else if(c->codec_id == AV_CODEC_ID_H264){
  45. return 3;
  46. }else if(c->codec_id == AV_CODEC_ID_MP3 || c->codec_id == AV_CODEC_ID_MP2){
  47. int lsf, mpeg25, sample_rate_index, bitrate_index, frame_size;
  48. int layer= c->codec_id == AV_CODEC_ID_MP3 ? 3 : 2;
  49. unsigned int header= 0xFFF00000;
  50. lsf = sample_rate < (24000+32000)/2;
  51. mpeg25 = sample_rate < (12000+16000)/2;
  52. sample_rate <<= lsf + mpeg25;
  53. if (sample_rate < (32000 + 44100)/2) sample_rate_index=2;
  54. else if(sample_rate < (44100 + 48000)/2) sample_rate_index=0;
  55. else sample_rate_index=1;
  56. sample_rate= avpriv_mpa_freq_tab[sample_rate_index] >> (lsf + mpeg25);
  57. for(bitrate_index=2; bitrate_index<30; bitrate_index++){
  58. frame_size = avpriv_mpa_bitrate_tab[lsf][layer-1][bitrate_index>>1];
  59. frame_size = (frame_size * 144000) / (sample_rate << lsf) + (bitrate_index&1);
  60. if(frame_size == size)
  61. break;
  62. }
  63. header |= (!lsf)<<19;
  64. header |= (4-layer)<<17;
  65. header |= 1<<16; //no crc
  66. AV_WB32(out, header);
  67. if(size <= 0)
  68. return 2; //we guess there is no crc, if there is one the user clearly does not care about overhead
  69. if(bitrate_index == 30)
  70. return -1; //something is wrong ...
  71. header |= (bitrate_index>>1)<<12;
  72. header |= sample_rate_index<<10;
  73. header |= (bitrate_index&1)<<9;
  74. return 2; //FIXME actually put the needed ones in build_elision_headers()
  75. return 3; //we guess that the private bit is not set
  76. //FIXME the above assumptions should be checked, if these turn out false too often something should be done
  77. }
  78. return 0;
  79. }
  80. static int find_header_idx(AVFormatContext *s, AVCodecContext *c, int size, int frame_type){
  81. NUTContext *nut = s->priv_data;
  82. uint8_t out[64];
  83. int i;
  84. int len= find_expected_header(c, size, frame_type, out);
  85. //av_log(NULL, AV_LOG_ERROR, "expected_h len=%d size=%d codec_id=%d\n", len, size, c->codec_id);
  86. for(i=1; i<nut->header_count; i++){
  87. if( len == nut->header_len[i]
  88. && !memcmp(out, nut->header[i], len)){
  89. // av_log(NULL, AV_LOG_ERROR, "found %d\n", i);
  90. return i;
  91. }
  92. }
  93. // av_log(NULL, AV_LOG_ERROR, "nothing found\n");
  94. return 0;
  95. }
  96. static void build_elision_headers(AVFormatContext *s){
  97. NUTContext *nut = s->priv_data;
  98. int i;
  99. //FIXME this is lame
  100. //FIXME write a 2pass mode to find the maximal headers
  101. static const uint8_t headers[][5]={
  102. {3, 0x00, 0x00, 0x01},
  103. {4, 0x00, 0x00, 0x01, 0xB6},
  104. {2, 0xFF, 0xFA}, //mp3+crc
  105. {2, 0xFF, 0xFB}, //mp3
  106. {2, 0xFF, 0xFC}, //mp2+crc
  107. {2, 0xFF, 0xFD}, //mp2
  108. };
  109. nut->header_count= 7;
  110. for(i=1; i<nut->header_count; i++){
  111. nut->header_len[i]= headers[i-1][0];
  112. nut->header [i]= &headers[i-1][1];
  113. }
  114. }
  115. static void build_frame_code(AVFormatContext *s){
  116. NUTContext *nut = s->priv_data;
  117. int key_frame, index, pred, stream_id;
  118. int start=1;
  119. int end= 254;
  120. int keyframe_0_esc= s->nb_streams > 2;
  121. int pred_table[10];
  122. FrameCode *ft;
  123. ft= &nut->frame_code[start];
  124. ft->flags= FLAG_CODED;
  125. ft->size_mul=1;
  126. ft->pts_delta=1;
  127. start++;
  128. if(keyframe_0_esc){
  129. /* keyframe = 0 escape */
  130. FrameCode *ft= &nut->frame_code[start];
  131. ft->flags= FLAG_STREAM_ID | FLAG_SIZE_MSB | FLAG_CODED_PTS;
  132. ft->size_mul=1;
  133. start++;
  134. }
  135. for(stream_id= 0; stream_id<s->nb_streams; stream_id++){
  136. int start2= start + (end-start)*stream_id / s->nb_streams;
  137. int end2 = start + (end-start)*(stream_id+1) / s->nb_streams;
  138. AVCodecContext *codec = s->streams[stream_id]->codec;
  139. int is_audio= codec->codec_type == AVMEDIA_TYPE_AUDIO;
  140. int intra_only= /*codec->intra_only || */is_audio;
  141. int pred_count;
  142. for(key_frame=0; key_frame<2; key_frame++){
  143. if(intra_only && keyframe_0_esc && key_frame==0)
  144. continue;
  145. {
  146. FrameCode *ft= &nut->frame_code[start2];
  147. ft->flags= FLAG_KEY*key_frame;
  148. ft->flags|= FLAG_SIZE_MSB | FLAG_CODED_PTS;
  149. ft->stream_id= stream_id;
  150. ft->size_mul=1;
  151. if(is_audio)
  152. ft->header_idx= find_header_idx(s, codec, -1, key_frame);
  153. start2++;
  154. }
  155. }
  156. key_frame= intra_only;
  157. #if 1
  158. if(is_audio){
  159. int frame_bytes= codec->frame_size*(int64_t)codec->bit_rate / (8*codec->sample_rate);
  160. int pts;
  161. for(pts=0; pts<2; pts++){
  162. for(pred=0; pred<2; pred++){
  163. FrameCode *ft= &nut->frame_code[start2];
  164. ft->flags= FLAG_KEY*key_frame;
  165. ft->stream_id= stream_id;
  166. ft->size_mul=frame_bytes + 2;
  167. ft->size_lsb=frame_bytes + pred;
  168. ft->pts_delta=pts;
  169. ft->header_idx= find_header_idx(s, codec, frame_bytes + pred, key_frame);
  170. start2++;
  171. }
  172. }
  173. }else{
  174. FrameCode *ft= &nut->frame_code[start2];
  175. ft->flags= FLAG_KEY | FLAG_SIZE_MSB;
  176. ft->stream_id= stream_id;
  177. ft->size_mul=1;
  178. ft->pts_delta=1;
  179. start2++;
  180. }
  181. #endif
  182. if(codec->has_b_frames){
  183. pred_count=5;
  184. pred_table[0]=-2;
  185. pred_table[1]=-1;
  186. pred_table[2]=1;
  187. pred_table[3]=3;
  188. pred_table[4]=4;
  189. }else if(codec->codec_id == AV_CODEC_ID_VORBIS){
  190. pred_count=3;
  191. pred_table[0]=2;
  192. pred_table[1]=9;
  193. pred_table[2]=16;
  194. }else{
  195. pred_count=1;
  196. pred_table[0]=1;
  197. }
  198. for(pred=0; pred<pred_count; pred++){
  199. int start3= start2 + (end2-start2)*pred / pred_count;
  200. int end3 = start2 + (end2-start2)*(pred+1) / pred_count;
  201. for(index=start3; index<end3; index++){
  202. FrameCode *ft= &nut->frame_code[index];
  203. ft->flags= FLAG_KEY*key_frame;
  204. ft->flags|= FLAG_SIZE_MSB;
  205. ft->stream_id= stream_id;
  206. //FIXME use single byte size and pred from last
  207. ft->size_mul= end3-start3;
  208. ft->size_lsb= index - start3;
  209. ft->pts_delta= pred_table[pred];
  210. if(is_audio)
  211. ft->header_idx= find_header_idx(s, codec, -1, key_frame);
  212. }
  213. }
  214. }
  215. memmove(&nut->frame_code['N'+1], &nut->frame_code['N'], sizeof(FrameCode)*(255-'N'));
  216. nut->frame_code[ 0].flags=
  217. nut->frame_code[255].flags=
  218. nut->frame_code['N'].flags= FLAG_INVALID;
  219. }
  220. static void put_tt(NUTContext *nut, AVRational *time_base, AVIOContext *bc, uint64_t val){
  221. val *= nut->time_base_count;
  222. val += time_base - nut->time_base;
  223. ff_put_v(bc, val);
  224. }
  225. /**
  226. * Store a string as vb.
  227. */
  228. static void put_str(AVIOContext *bc, const char *string){
  229. int len= strlen(string);
  230. ff_put_v(bc, len);
  231. avio_write(bc, string, len);
  232. }
  233. static void put_s(AVIOContext *bc, int64_t val){
  234. ff_put_v(bc, 2*FFABS(val) - (val>0));
  235. }
  236. #ifdef TRACE
  237. static inline void ff_put_v_trace(AVIOContext *bc, uint64_t v, char *file, char *func, int line){
  238. av_log(NULL, AV_LOG_DEBUG, "ff_put_v %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  239. ff_put_v(bc, v);
  240. }
  241. static inline void put_s_trace(AVIOContext *bc, int64_t v, char *file, char *func, int line){
  242. av_log(NULL, AV_LOG_DEBUG, "put_s %5"PRId64" / %"PRIX64" in %s %s:%d\n", v, v, file, func, line);
  243. put_s(bc, v);
  244. }
  245. #define ff_put_v(bc, v) ff_put_v_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  246. #define put_s(bc, v) put_s_trace(bc, v, __FILE__, __PRETTY_FUNCTION__, __LINE__)
  247. #endif
  248. //FIXME remove calculate_checksum
  249. static void put_packet(NUTContext *nut, AVIOContext *bc, AVIOContext *dyn_bc, int calculate_checksum, uint64_t startcode){
  250. uint8_t *dyn_buf=NULL;
  251. int dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
  252. int forw_ptr= dyn_size + 4*calculate_checksum;
  253. if(forw_ptr > 4096)
  254. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  255. avio_wb64(bc, startcode);
  256. ff_put_v(bc, forw_ptr);
  257. if(forw_ptr > 4096)
  258. avio_wl32(bc, ffio_get_checksum(bc));
  259. if(calculate_checksum)
  260. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  261. avio_write(bc, dyn_buf, dyn_size);
  262. if(calculate_checksum)
  263. avio_wl32(bc, ffio_get_checksum(bc));
  264. av_free(dyn_buf);
  265. }
  266. static void write_mainheader(NUTContext *nut, AVIOContext *bc){
  267. int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields, tmp_head_idx;
  268. int64_t tmp_match;
  269. ff_put_v(bc, 3); /* version */
  270. ff_put_v(bc, nut->avf->nb_streams);
  271. ff_put_v(bc, nut->max_distance);
  272. ff_put_v(bc, nut->time_base_count);
  273. for(i=0; i<nut->time_base_count; i++){
  274. ff_put_v(bc, nut->time_base[i].num);
  275. ff_put_v(bc, nut->time_base[i].den);
  276. }
  277. tmp_pts=0;
  278. tmp_mul=1;
  279. tmp_stream=0;
  280. tmp_match= 1-(1LL<<62);
  281. tmp_head_idx= 0;
  282. for(i=0; i<256;){
  283. tmp_fields=0;
  284. tmp_size=0;
  285. // tmp_res=0;
  286. if(tmp_pts != nut->frame_code[i].pts_delta) tmp_fields=1;
  287. if(tmp_mul != nut->frame_code[i].size_mul ) tmp_fields=2;
  288. if(tmp_stream != nut->frame_code[i].stream_id) tmp_fields=3;
  289. if(tmp_size != nut->frame_code[i].size_lsb ) tmp_fields=4;
  290. // if(tmp_res != nut->frame_code[i].res ) tmp_fields=5;
  291. if(tmp_head_idx!=nut->frame_code[i].header_idx)tmp_fields=8;
  292. tmp_pts = nut->frame_code[i].pts_delta;
  293. tmp_flags = nut->frame_code[i].flags;
  294. tmp_stream= nut->frame_code[i].stream_id;
  295. tmp_mul = nut->frame_code[i].size_mul;
  296. tmp_size = nut->frame_code[i].size_lsb;
  297. // tmp_res = nut->frame_code[i].res;
  298. tmp_head_idx= nut->frame_code[i].header_idx;
  299. for(j=0; i<256; j++,i++){
  300. if(i == 'N'){
  301. j--;
  302. continue;
  303. }
  304. if(nut->frame_code[i].pts_delta != tmp_pts ) break;
  305. if(nut->frame_code[i].flags != tmp_flags ) break;
  306. if(nut->frame_code[i].stream_id != tmp_stream) break;
  307. if(nut->frame_code[i].size_mul != tmp_mul ) break;
  308. if(nut->frame_code[i].size_lsb != tmp_size+j) break;
  309. // if(nut->frame_code[i].res != tmp_res ) break;
  310. if(nut->frame_code[i].header_idx!= tmp_head_idx) break;
  311. }
  312. if(j != tmp_mul - tmp_size) tmp_fields=6;
  313. ff_put_v(bc, tmp_flags);
  314. ff_put_v(bc, tmp_fields);
  315. if(tmp_fields>0) put_s(bc, tmp_pts);
  316. if(tmp_fields>1) ff_put_v(bc, tmp_mul);
  317. if(tmp_fields>2) ff_put_v(bc, tmp_stream);
  318. if(tmp_fields>3) ff_put_v(bc, tmp_size);
  319. if(tmp_fields>4) ff_put_v(bc, 0 /*tmp_res*/);
  320. if(tmp_fields>5) ff_put_v(bc, j);
  321. if(tmp_fields>6) ff_put_v(bc, tmp_match);
  322. if(tmp_fields>7) ff_put_v(bc, tmp_head_idx);
  323. }
  324. ff_put_v(bc, nut->header_count-1);
  325. for(i=1; i<nut->header_count; i++){
  326. ff_put_v(bc, nut->header_len[i]);
  327. avio_write(bc, nut->header[i], nut->header_len[i]);
  328. }
  329. }
  330. static int write_streamheader(AVFormatContext *avctx, AVIOContext *bc, AVStream *st, int i){
  331. NUTContext *nut = avctx->priv_data;
  332. AVCodecContext *codec = st->codec;
  333. ff_put_v(bc, i);
  334. switch(codec->codec_type){
  335. case AVMEDIA_TYPE_VIDEO: ff_put_v(bc, 0); break;
  336. case AVMEDIA_TYPE_AUDIO: ff_put_v(bc, 1); break;
  337. case AVMEDIA_TYPE_SUBTITLE: ff_put_v(bc, 2); break;
  338. default : ff_put_v(bc, 3); break;
  339. }
  340. ff_put_v(bc, 4);
  341. if (codec->codec_tag){
  342. avio_wl32(bc, codec->codec_tag);
  343. } else {
  344. av_log(avctx, AV_LOG_ERROR, "No codec tag defined for stream %d\n", i);
  345. return AVERROR(EINVAL);
  346. }
  347. ff_put_v(bc, nut->stream[i].time_base - nut->time_base);
  348. ff_put_v(bc, nut->stream[i].msb_pts_shift);
  349. ff_put_v(bc, nut->stream[i].max_pts_distance);
  350. ff_put_v(bc, codec->has_b_frames);
  351. avio_w8(bc, 0); /* flags: 0x1 - fixed_fps, 0x2 - index_present */
  352. ff_put_v(bc, codec->extradata_size);
  353. avio_write(bc, codec->extradata, codec->extradata_size);
  354. switch(codec->codec_type){
  355. case AVMEDIA_TYPE_AUDIO:
  356. ff_put_v(bc, codec->sample_rate);
  357. ff_put_v(bc, 1);
  358. ff_put_v(bc, codec->channels);
  359. break;
  360. case AVMEDIA_TYPE_VIDEO:
  361. ff_put_v(bc, codec->width);
  362. ff_put_v(bc, codec->height);
  363. if(st->sample_aspect_ratio.num<=0 || st->sample_aspect_ratio.den<=0){
  364. ff_put_v(bc, 0);
  365. ff_put_v(bc, 0);
  366. }else{
  367. ff_put_v(bc, st->sample_aspect_ratio.num);
  368. ff_put_v(bc, st->sample_aspect_ratio.den);
  369. }
  370. ff_put_v(bc, 0); /* csp type -- unknown */
  371. break;
  372. default:
  373. break;
  374. }
  375. return 0;
  376. }
  377. static int add_info(AVIOContext *bc, const char *type, const char *value){
  378. put_str(bc, type);
  379. put_s(bc, -1);
  380. put_str(bc, value);
  381. return 1;
  382. }
  383. static int write_globalinfo(NUTContext *nut, AVIOContext *bc){
  384. AVFormatContext *s= nut->avf;
  385. AVDictionaryEntry *t = NULL;
  386. AVIOContext *dyn_bc;
  387. uint8_t *dyn_buf=NULL;
  388. int count=0, dyn_size;
  389. int ret = avio_open_dyn_buf(&dyn_bc);
  390. if(ret < 0)
  391. return ret;
  392. while ((t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
  393. count += add_info(dyn_bc, t->key, t->value);
  394. ff_put_v(bc, 0); //stream_if_plus1
  395. ff_put_v(bc, 0); //chapter_id
  396. ff_put_v(bc, 0); //timestamp_start
  397. ff_put_v(bc, 0); //length
  398. ff_put_v(bc, count);
  399. dyn_size= avio_close_dyn_buf(dyn_bc, &dyn_buf);
  400. avio_write(bc, dyn_buf, dyn_size);
  401. av_free(dyn_buf);
  402. return 0;
  403. }
  404. static int write_streaminfo(NUTContext *nut, AVIOContext *bc, int stream_id){
  405. AVFormatContext *s= nut->avf;
  406. AVStream* st = s->streams[stream_id];
  407. AVDictionaryEntry *t = NULL;
  408. AVIOContext *dyn_bc;
  409. uint8_t *dyn_buf=NULL;
  410. int count=0, dyn_size, i;
  411. int ret = avio_open_dyn_buf(&dyn_bc);
  412. if(ret < 0)
  413. return ret;
  414. while ((t = av_dict_get(st->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
  415. count += add_info(dyn_bc, t->key, t->value);
  416. for (i=0; ff_nut_dispositions[i].flag; ++i) {
  417. if (st->disposition & ff_nut_dispositions[i].flag)
  418. count += add_info(dyn_bc, "Disposition", ff_nut_dispositions[i].str);
  419. }
  420. dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
  421. if (count) {
  422. ff_put_v(bc, stream_id + 1); //stream_id_plus1
  423. ff_put_v(bc, 0); //chapter_id
  424. ff_put_v(bc, 0); //timestamp_start
  425. ff_put_v(bc, 0); //length
  426. ff_put_v(bc, count);
  427. avio_write(bc, dyn_buf, dyn_size);
  428. }
  429. av_free(dyn_buf);
  430. return count;
  431. }
  432. static int write_chapter(NUTContext *nut, AVIOContext *bc, int id)
  433. {
  434. AVIOContext *dyn_bc;
  435. uint8_t *dyn_buf = NULL;
  436. AVDictionaryEntry *t = NULL;
  437. AVChapter *ch = nut->avf->chapters[id];
  438. int ret, dyn_size, count = 0;
  439. ret = avio_open_dyn_buf(&dyn_bc);
  440. if (ret < 0)
  441. return ret;
  442. ff_put_v(bc, 0); // stream_id_plus1
  443. put_s(bc, id + 1); // chapter_id
  444. put_tt(nut, nut->chapter[id].time_base, bc, ch->start); // chapter_start
  445. ff_put_v(bc, ch->end - ch->start); // chapter_len
  446. while ((t = av_dict_get(ch->metadata, "", t, AV_DICT_IGNORE_SUFFIX)))
  447. count += add_info(dyn_bc, t->key, t->value);
  448. ff_put_v(bc, count);
  449. dyn_size = avio_close_dyn_buf(dyn_bc, &dyn_buf);
  450. avio_write(bc, dyn_buf, dyn_size);
  451. av_freep(&dyn_buf);
  452. return 0;
  453. }
  454. static int write_index(NUTContext *nut, AVIOContext *bc){
  455. int i;
  456. Syncpoint dummy= { .pos= 0 };
  457. Syncpoint *next_node[2] = { NULL };
  458. int64_t startpos = avio_tell(bc);
  459. int64_t payload_size;
  460. put_tt(nut, nut->max_pts_tb, bc, nut->max_pts);
  461. ff_put_v(bc, nut->sp_count);
  462. for(i=0; i<nut->sp_count; i++){
  463. av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp, (void**)next_node);
  464. ff_put_v(bc, (next_node[1]->pos >> 4) - (dummy.pos>>4));
  465. dummy.pos = next_node[1]->pos;
  466. }
  467. for(i=0; i<nut->avf->nb_streams; i++){
  468. StreamContext *nus= &nut->stream[i];
  469. int64_t last_pts= -1;
  470. int j, k;
  471. for(j=0; j<nut->sp_count; j++){
  472. int flag = (nus->keyframe_pts[j] != AV_NOPTS_VALUE) ^ (j+1 == nut->sp_count);
  473. int n = 0;
  474. for(; j<nut->sp_count && (nus->keyframe_pts[j] != AV_NOPTS_VALUE) == flag; j++)
  475. n++;
  476. ff_put_v(bc, 1 + 2*flag + 4*n);
  477. for(k= j - n; k<=j && k<nut->sp_count; k++) {
  478. if(nus->keyframe_pts[k] == AV_NOPTS_VALUE)
  479. continue;
  480. av_assert0(nus->keyframe_pts[k] > last_pts);
  481. ff_put_v(bc, nus->keyframe_pts[k] - last_pts);
  482. last_pts = nus->keyframe_pts[k];
  483. }
  484. }
  485. }
  486. payload_size = avio_tell(bc) - startpos + 8 + 4;
  487. avio_wb64(bc, 8 + payload_size + av_log2(payload_size) / 7 + 1 + 4*(payload_size > 4096));
  488. return 0;
  489. }
  490. static int write_headers(AVFormatContext *avctx, AVIOContext *bc){
  491. NUTContext *nut = avctx->priv_data;
  492. AVIOContext *dyn_bc;
  493. int i, ret;
  494. ff_metadata_conv_ctx(avctx, ff_nut_metadata_conv, NULL);
  495. ret = avio_open_dyn_buf(&dyn_bc);
  496. if(ret < 0)
  497. return ret;
  498. write_mainheader(nut, dyn_bc);
  499. put_packet(nut, bc, dyn_bc, 1, MAIN_STARTCODE);
  500. for (i=0; i < nut->avf->nb_streams; i++){
  501. ret = avio_open_dyn_buf(&dyn_bc);
  502. if(ret < 0)
  503. return ret;
  504. if ((ret = write_streamheader(avctx, dyn_bc, nut->avf->streams[i], i)) < 0)
  505. return ret;
  506. put_packet(nut, bc, dyn_bc, 1, STREAM_STARTCODE);
  507. }
  508. ret = avio_open_dyn_buf(&dyn_bc);
  509. if(ret < 0)
  510. return ret;
  511. write_globalinfo(nut, dyn_bc);
  512. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  513. for (i = 0; i < nut->avf->nb_streams; i++) {
  514. ret = avio_open_dyn_buf(&dyn_bc);
  515. if(ret < 0)
  516. return ret;
  517. ret = write_streaminfo(nut, dyn_bc, i);
  518. if (ret < 0)
  519. return ret;
  520. if (ret > 0)
  521. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  522. else {
  523. uint8_t* buf;
  524. avio_close_dyn_buf(dyn_bc, &buf);
  525. av_free(buf);
  526. }
  527. }
  528. for (i = 0; i < nut->avf->nb_chapters; i++) {
  529. ret = avio_open_dyn_buf(&dyn_bc);
  530. if (ret < 0)
  531. return ret;
  532. ret = write_chapter(nut, dyn_bc, i);
  533. if (ret < 0) {
  534. uint8_t *buf;
  535. avio_close_dyn_buf(dyn_bc, &buf);
  536. av_freep(&buf);
  537. return ret;
  538. }
  539. put_packet(nut, bc, dyn_bc, 1, INFO_STARTCODE);
  540. }
  541. nut->last_syncpoint_pos= INT_MIN;
  542. nut->header_count++;
  543. return 0;
  544. }
  545. static int nut_write_header(AVFormatContext *s){
  546. NUTContext *nut = s->priv_data;
  547. AVIOContext *bc = s->pb;
  548. int i, j, ret;
  549. nut->avf= s;
  550. nut->stream = av_mallocz(sizeof(StreamContext)*s->nb_streams);
  551. nut->chapter = av_mallocz(sizeof(ChapterContext)*s->nb_chapters);
  552. nut->time_base= av_mallocz(sizeof(AVRational )*(s->nb_streams +
  553. s->nb_chapters));
  554. if (!nut->stream || !nut->chapter || !nut->time_base) {
  555. av_freep(&nut->stream);
  556. av_freep(&nut->chapter);
  557. av_freep(&nut->time_base);
  558. return AVERROR(ENOMEM);
  559. }
  560. for(i=0; i<s->nb_streams; i++){
  561. AVStream *st= s->streams[i];
  562. int ssize;
  563. AVRational time_base;
  564. ff_parse_specific_params(st->codec, &time_base.den, &ssize, &time_base.num);
  565. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  566. for(j=0; j<nut->time_base_count; j++){
  567. if(!memcmp(&time_base, &nut->time_base[j], sizeof(AVRational))){
  568. break;
  569. }
  570. }
  571. nut->time_base[j]= time_base;
  572. nut->stream[i].time_base= &nut->time_base[j];
  573. if(j==nut->time_base_count)
  574. nut->time_base_count++;
  575. if(INT64_C(1000) * time_base.num >= time_base.den)
  576. nut->stream[i].msb_pts_shift = 7;
  577. else
  578. nut->stream[i].msb_pts_shift = 14;
  579. nut->stream[i].max_pts_distance= FFMAX(time_base.den, time_base.num) / time_base.num;
  580. }
  581. for (i = 0; i < s->nb_chapters; i++) {
  582. AVChapter *ch = s->chapters[i];
  583. for (j = 0; j < nut->time_base_count; j++) {
  584. if (!memcmp(&ch->time_base, &nut->time_base[j], sizeof(AVRational)))
  585. break;
  586. }
  587. nut->time_base[j] = ch->time_base;
  588. nut->chapter[i].time_base = &nut->time_base[j];
  589. if(j == nut->time_base_count)
  590. nut->time_base_count++;
  591. }
  592. nut->max_distance = MAX_DISTANCE;
  593. build_elision_headers(s);
  594. build_frame_code(s);
  595. av_assert0(nut->frame_code['N'].flags == FLAG_INVALID);
  596. avio_write(bc, ID_STRING, strlen(ID_STRING));
  597. avio_w8(bc, 0);
  598. if ((ret = write_headers(s, bc)) < 0)
  599. return ret;
  600. if (s->avoid_negative_ts < 0)
  601. s->avoid_negative_ts = 1;
  602. avio_flush(bc);
  603. return 0;
  604. }
  605. static int get_needed_flags(NUTContext *nut, StreamContext *nus, FrameCode *fc, AVPacket *pkt){
  606. int flags= 0;
  607. if(pkt->flags & AV_PKT_FLAG_KEY ) flags |= FLAG_KEY;
  608. if(pkt->stream_index != fc->stream_id ) flags |= FLAG_STREAM_ID;
  609. if(pkt->size / fc->size_mul ) flags |= FLAG_SIZE_MSB;
  610. if(pkt->pts - nus->last_pts != fc->pts_delta) flags |= FLAG_CODED_PTS;
  611. if(pkt->size > 2*nut->max_distance ) flags |= FLAG_CHECKSUM;
  612. if(FFABS(pkt->pts - nus->last_pts)
  613. > nus->max_pts_distance) flags |= FLAG_CHECKSUM;
  614. if( pkt->size < nut->header_len[fc->header_idx]
  615. || (pkt->size > 4096 && fc->header_idx)
  616. || memcmp(pkt->data, nut->header[fc->header_idx], nut->header_len[fc->header_idx]))
  617. flags |= FLAG_HEADER_IDX;
  618. return flags | (fc->flags & FLAG_CODED);
  619. }
  620. static int find_best_header_idx(NUTContext *nut, AVPacket *pkt){
  621. int i;
  622. int best_i = 0;
  623. int best_len= 0;
  624. if(pkt->size > 4096)
  625. return 0;
  626. for(i=1; i<nut->header_count; i++){
  627. if( pkt->size >= nut->header_len[i]
  628. && nut->header_len[i] > best_len
  629. && !memcmp(pkt->data, nut->header[i], nut->header_len[i])){
  630. best_i= i;
  631. best_len= nut->header_len[i];
  632. }
  633. }
  634. return best_i;
  635. }
  636. static int nut_write_packet(AVFormatContext *s, AVPacket *pkt){
  637. NUTContext *nut = s->priv_data;
  638. StreamContext *nus= &nut->stream[pkt->stream_index];
  639. AVIOContext *bc = s->pb, *dyn_bc;
  640. FrameCode *fc;
  641. int64_t coded_pts;
  642. int best_length, frame_code, flags, needed_flags, i, header_idx, best_header_idx;
  643. int key_frame = !!(pkt->flags & AV_PKT_FLAG_KEY);
  644. int store_sp=0;
  645. int ret;
  646. if (pkt->pts < 0) {
  647. av_log(s, AV_LOG_ERROR, "Invalid negative packet pts %"PRId64" in input\n", pkt->pts);
  648. return AVERROR(EINVAL);
  649. }
  650. if(1LL<<(20+3*nut->header_count) <= avio_tell(bc))
  651. write_headers(s, bc);
  652. if(key_frame && !(nus->last_flags & FLAG_KEY))
  653. store_sp= 1;
  654. if(pkt->size + 30/*FIXME check*/ + avio_tell(bc) >= nut->last_syncpoint_pos + nut->max_distance)
  655. store_sp= 1;
  656. //FIXME: Ensure store_sp is 1 in the first place.
  657. if(store_sp){
  658. Syncpoint *sp, dummy= {.pos= INT64_MAX};
  659. ff_nut_reset_ts(nut, *nus->time_base, pkt->dts);
  660. for(i=0; i<s->nb_streams; i++){
  661. AVStream *st= s->streams[i];
  662. int64_t dts_tb = av_rescale_rnd(pkt->dts,
  663. nus->time_base->num * (int64_t)nut->stream[i].time_base->den,
  664. nus->time_base->den * (int64_t)nut->stream[i].time_base->num,
  665. AV_ROUND_DOWN);
  666. int index= av_index_search_timestamp(st, dts_tb, AVSEEK_FLAG_BACKWARD);
  667. if(index>=0) dummy.pos= FFMIN(dummy.pos, st->index_entries[index].pos);
  668. }
  669. if(dummy.pos == INT64_MAX)
  670. dummy.pos= 0;
  671. sp= av_tree_find(nut->syncpoints, &dummy, (void *) ff_nut_sp_pos_cmp,
  672. NULL);
  673. nut->last_syncpoint_pos= avio_tell(bc);
  674. ret = avio_open_dyn_buf(&dyn_bc);
  675. if(ret < 0)
  676. return ret;
  677. put_tt(nut, nus->time_base, dyn_bc, pkt->dts);
  678. ff_put_v(dyn_bc, sp ? (nut->last_syncpoint_pos - sp->pos)>>4 : 0);
  679. put_packet(nut, bc, dyn_bc, 1, SYNCPOINT_STARTCODE);
  680. ff_nut_add_sp(nut, nut->last_syncpoint_pos, 0/*unused*/, pkt->dts);
  681. if((1ll<<60) % nut->sp_count == 0)
  682. for(i=0; i<s->nb_streams; i++){
  683. int j;
  684. StreamContext *nus = &nut->stream[i];
  685. nus->keyframe_pts = av_realloc(nus->keyframe_pts, 2*nut->sp_count*sizeof(*nus->keyframe_pts));
  686. if(!nus->keyframe_pts)
  687. return AVERROR(ENOMEM);
  688. for(j=nut->sp_count == 1 ? 0 : nut->sp_count; j<2*nut->sp_count; j++)
  689. nus->keyframe_pts[j] = AV_NOPTS_VALUE;
  690. }
  691. }
  692. av_assert0(nus->last_pts != AV_NOPTS_VALUE);
  693. coded_pts = pkt->pts & ((1<<nus->msb_pts_shift)-1);
  694. if(ff_lsb2full(nus, coded_pts) != pkt->pts)
  695. coded_pts= pkt->pts + (1<<nus->msb_pts_shift);
  696. best_header_idx= find_best_header_idx(nut, pkt);
  697. best_length=INT_MAX;
  698. frame_code= -1;
  699. for(i=0; i<256; i++){
  700. int length= 0;
  701. FrameCode *fc= &nut->frame_code[i];
  702. int flags= fc->flags;
  703. if(flags & FLAG_INVALID)
  704. continue;
  705. needed_flags= get_needed_flags(nut, nus, fc, pkt);
  706. if(flags & FLAG_CODED){
  707. length++;
  708. flags = needed_flags;
  709. }
  710. if((flags & needed_flags) != needed_flags)
  711. continue;
  712. if((flags ^ needed_flags) & FLAG_KEY)
  713. continue;
  714. if(flags & FLAG_STREAM_ID)
  715. length+= ff_get_v_length(pkt->stream_index);
  716. if(pkt->size % fc->size_mul != fc->size_lsb)
  717. continue;
  718. if(flags & FLAG_SIZE_MSB)
  719. length += ff_get_v_length(pkt->size / fc->size_mul);
  720. if(flags & FLAG_CHECKSUM)
  721. length+=4;
  722. if(flags & FLAG_CODED_PTS)
  723. length += ff_get_v_length(coded_pts);
  724. if( (flags & FLAG_CODED)
  725. && nut->header_len[best_header_idx] > nut->header_len[fc->header_idx]+1){
  726. flags |= FLAG_HEADER_IDX;
  727. }
  728. if(flags & FLAG_HEADER_IDX){
  729. length += 1 - nut->header_len[best_header_idx];
  730. }else{
  731. length -= nut->header_len[fc->header_idx];
  732. }
  733. length*=4;
  734. length+= !(flags & FLAG_CODED_PTS);
  735. length+= !(flags & FLAG_CHECKSUM);
  736. if(length < best_length){
  737. best_length= length;
  738. frame_code=i;
  739. }
  740. }
  741. av_assert0(frame_code != -1);
  742. fc= &nut->frame_code[frame_code];
  743. flags= fc->flags;
  744. needed_flags= get_needed_flags(nut, nus, fc, pkt);
  745. header_idx= fc->header_idx;
  746. ffio_init_checksum(bc, ff_crc04C11DB7_update, 0);
  747. avio_w8(bc, frame_code);
  748. if(flags & FLAG_CODED){
  749. ff_put_v(bc, (flags^needed_flags) & ~(FLAG_CODED));
  750. flags = needed_flags;
  751. }
  752. if(flags & FLAG_STREAM_ID) ff_put_v(bc, pkt->stream_index);
  753. if(flags & FLAG_CODED_PTS) ff_put_v(bc, coded_pts);
  754. if(flags & FLAG_SIZE_MSB) ff_put_v(bc, pkt->size / fc->size_mul);
  755. if(flags & FLAG_HEADER_IDX) ff_put_v(bc, header_idx= best_header_idx);
  756. if(flags & FLAG_CHECKSUM) avio_wl32(bc, ffio_get_checksum(bc));
  757. else ffio_get_checksum(bc);
  758. avio_write(bc, pkt->data + nut->header_len[header_idx], pkt->size - nut->header_len[header_idx]);
  759. nus->last_flags= flags;
  760. nus->last_pts= pkt->pts;
  761. //FIXME just store one per syncpoint
  762. if(flags & FLAG_KEY) {
  763. av_add_index_entry(
  764. s->streams[pkt->stream_index],
  765. nut->last_syncpoint_pos,
  766. pkt->pts,
  767. 0,
  768. 0,
  769. AVINDEX_KEYFRAME);
  770. if(nus->keyframe_pts && nus->keyframe_pts[nut->sp_count] == AV_NOPTS_VALUE)
  771. nus->keyframe_pts[nut->sp_count] = pkt->pts;
  772. }
  773. if(!nut->max_pts_tb || av_compare_ts(nut->max_pts, *nut->max_pts_tb, pkt->pts, *nus->time_base) < 0) {
  774. nut->max_pts = pkt->pts;
  775. nut->max_pts_tb = nus->time_base;
  776. }
  777. return 0;
  778. }
  779. static int nut_write_trailer(AVFormatContext *s){
  780. NUTContext *nut= s->priv_data;
  781. AVIOContext *bc = s->pb, *dyn_bc;
  782. int i, ret;
  783. while(nut->header_count<3)
  784. write_headers(s, bc);
  785. ret = avio_open_dyn_buf(&dyn_bc);
  786. if(ret >= 0) {
  787. write_index(nut, dyn_bc);
  788. put_packet(nut, bc, dyn_bc, 1, INDEX_STARTCODE);
  789. }
  790. ff_nut_free_sp(nut);
  791. for(i=0; i<s->nb_streams; i++)
  792. av_freep(&nut->stream[i].keyframe_pts);
  793. av_freep(&nut->stream);
  794. av_freep(&nut->chapter);
  795. av_freep(&nut->time_base);
  796. return 0;
  797. }
  798. AVOutputFormat ff_nut_muxer = {
  799. .name = "nut",
  800. .long_name = NULL_IF_CONFIG_SMALL("NUT"),
  801. .mime_type = "video/x-nut",
  802. .extensions = "nut",
  803. .priv_data_size = sizeof(NUTContext),
  804. .audio_codec = CONFIG_LIBVORBIS ? AV_CODEC_ID_VORBIS :
  805. CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_MP2,
  806. .video_codec = AV_CODEC_ID_MPEG4,
  807. .write_header = nut_write_header,
  808. .write_packet = nut_write_packet,
  809. .write_trailer = nut_write_trailer,
  810. .flags = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
  811. .codec_tag = (const AVCodecTag * const []){
  812. ff_codec_bmp_tags, ff_nut_video_tags, ff_codec_wav_tags,
  813. ff_nut_subtitle_tags, 0
  814. },
  815. };