movenchint.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * MOV, 3GP, MP4 muxer RTP hinting
  3. * Copyright (c) 2010 Martin Storsjo
  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 "movenc.h"
  22. #include "libavutil/intreadwrite.h"
  23. #include "internal.h"
  24. #include "rtpenc_chain.h"
  25. #include "avio_internal.h"
  26. int ff_mov_init_hinting(AVFormatContext *s, int index, int src_index)
  27. {
  28. MOVMuxContext *mov = s->priv_data;
  29. MOVTrack *track = &mov->tracks[index];
  30. MOVTrack *src_track = &mov->tracks[src_index];
  31. AVStream *src_st = s->streams[src_index];
  32. int ret = AVERROR(ENOMEM);
  33. track->tag = MKTAG('r','t','p',' ');
  34. track->src_track = src_index;
  35. track->enc = avcodec_alloc_context3(NULL);
  36. if (!track->enc)
  37. goto fail;
  38. track->enc->codec_type = AVMEDIA_TYPE_DATA;
  39. track->enc->codec_tag = track->tag;
  40. track->rtp_ctx = ff_rtp_chain_mux_open(s, src_st, NULL,
  41. RTP_MAX_PACKET_SIZE);
  42. if (!track->rtp_ctx)
  43. goto fail;
  44. /* Copy the RTP AVStream timebase back to the hint AVStream */
  45. track->timescale = track->rtp_ctx->streams[0]->time_base.den;
  46. /* Mark the hinted track that packets written to it should be
  47. * sent to this track for hinting. */
  48. src_track->hint_track = index;
  49. return 0;
  50. fail:
  51. av_log(s, AV_LOG_WARNING,
  52. "Unable to initialize hinting of stream %d\n", src_index);
  53. av_freep(&track->enc);
  54. /* Set a default timescale, to avoid crashes in av_dump_format */
  55. track->timescale = 90000;
  56. return ret;
  57. }
  58. /**
  59. * Remove the first sample from the sample queue.
  60. */
  61. static void sample_queue_pop(HintSampleQueue *queue)
  62. {
  63. if (queue->len <= 0)
  64. return;
  65. if (queue->samples[0].own_data)
  66. av_free(queue->samples[0].data);
  67. queue->len--;
  68. memmove(queue->samples, queue->samples + 1, sizeof(HintSample)*queue->len);
  69. }
  70. /**
  71. * Empty the sample queue, releasing all memory.
  72. */
  73. static void sample_queue_free(HintSampleQueue *queue)
  74. {
  75. int i;
  76. for (i = 0; i < queue->len; i++)
  77. if (queue->samples[i].own_data)
  78. av_free(queue->samples[i].data);
  79. av_freep(&queue->samples);
  80. queue->len = 0;
  81. queue->size = 0;
  82. }
  83. /**
  84. * Add a reference to the sample data to the sample queue. The data is
  85. * not copied. sample_queue_retain should be called before pkt->data
  86. * is reused/freed.
  87. */
  88. static void sample_queue_push(HintSampleQueue *queue, AVPacket *pkt, int sample)
  89. {
  90. /* No need to keep track of smaller samples, since describing them
  91. * with immediates is more efficient. */
  92. if (pkt->size <= 14)
  93. return;
  94. if (!queue->samples || queue->len >= queue->size) {
  95. HintSample* samples;
  96. queue->size += 10;
  97. samples = av_realloc(queue->samples, sizeof(HintSample)*queue->size);
  98. if (!samples)
  99. return;
  100. queue->samples = samples;
  101. }
  102. queue->samples[queue->len].data = pkt->data;
  103. queue->samples[queue->len].size = pkt->size;
  104. queue->samples[queue->len].sample_number = sample;
  105. queue->samples[queue->len].offset = 0;
  106. queue->samples[queue->len].own_data = 0;
  107. queue->len++;
  108. }
  109. /**
  110. * Make local copies of all referenced sample data in the queue.
  111. */
  112. static void sample_queue_retain(HintSampleQueue *queue)
  113. {
  114. int i;
  115. for (i = 0; i < queue->len; ) {
  116. HintSample *sample = &queue->samples[i];
  117. if (!sample->own_data) {
  118. uint8_t* ptr = av_malloc(sample->size);
  119. if (!ptr) {
  120. /* Unable to allocate memory for this one, remove it */
  121. memmove(queue->samples + i, queue->samples + i + 1,
  122. sizeof(HintSample)*(queue->len - i - 1));
  123. queue->len--;
  124. continue;
  125. }
  126. memcpy(ptr, sample->data, sample->size);
  127. sample->data = ptr;
  128. sample->own_data = 1;
  129. }
  130. i++;
  131. }
  132. }
  133. /**
  134. * Find matches of needle[n_pos ->] within haystack. If a sufficiently
  135. * large match is found, matching bytes before n_pos are included
  136. * in the match, too (within the limits of the arrays).
  137. *
  138. * @param haystack buffer that may contain parts of needle
  139. * @param h_len length of the haystack buffer
  140. * @param needle buffer containing source data that have been used to
  141. * construct haystack
  142. * @param n_pos start position in needle used for looking for matches
  143. * @param n_len length of the needle buffer
  144. * @param match_h_offset_ptr offset of the first matching byte within haystack
  145. * @param match_n_offset_ptr offset of the first matching byte within needle
  146. * @param match_len_ptr length of the matched segment
  147. * @return 0 if a match was found, < 0 if no match was found
  148. */
  149. static int match_segments(const uint8_t *haystack, int h_len,
  150. const uint8_t *needle, int n_pos, int n_len,
  151. int *match_h_offset_ptr, int *match_n_offset_ptr,
  152. int *match_len_ptr)
  153. {
  154. int h_pos;
  155. for (h_pos = 0; h_pos < h_len; h_pos++) {
  156. int match_len = 0;
  157. int match_h_pos, match_n_pos;
  158. /* Check how many bytes match at needle[n_pos] and haystack[h_pos] */
  159. while (h_pos + match_len < h_len && n_pos + match_len < n_len &&
  160. needle[n_pos + match_len] == haystack[h_pos + match_len])
  161. match_len++;
  162. if (match_len <= 8)
  163. continue;
  164. /* If a sufficiently large match was found, try to expand
  165. * the matched segment backwards. */
  166. match_h_pos = h_pos;
  167. match_n_pos = n_pos;
  168. while (match_n_pos > 0 && match_h_pos > 0 &&
  169. needle[match_n_pos - 1] == haystack[match_h_pos - 1]) {
  170. match_n_pos--;
  171. match_h_pos--;
  172. match_len++;
  173. }
  174. if (match_len <= 14)
  175. continue;
  176. *match_h_offset_ptr = match_h_pos;
  177. *match_n_offset_ptr = match_n_pos;
  178. *match_len_ptr = match_len;
  179. return 0;
  180. }
  181. return -1;
  182. }
  183. /**
  184. * Look for segments in samples in the sample queue matching the data
  185. * in ptr. Samples not matching are removed from the queue. If a match
  186. * is found, the next time it will look for matches starting from the
  187. * end of the previous matched segment.
  188. *
  189. * @param data data to find matches for in the sample queue
  190. * @param len length of the data buffer
  191. * @param queue samples used for looking for matching segments
  192. * @param pos the offset in data of the matched segment
  193. * @param match_sample the number of the sample that contained the match
  194. * @param match_offset the offset of the matched segment within the sample
  195. * @param match_len the length of the matched segment
  196. * @return 0 if a match was found, < 0 if no match was found
  197. */
  198. static int find_sample_match(const uint8_t *data, int len,
  199. HintSampleQueue *queue, int *pos,
  200. int *match_sample, int *match_offset,
  201. int *match_len)
  202. {
  203. while (queue->len > 0) {
  204. HintSample *sample = &queue->samples[0];
  205. /* If looking for matches in a new sample, skip the first 5 bytes,
  206. * since they often may be modified/removed in the output packet. */
  207. if (sample->offset == 0 && sample->size > 5)
  208. sample->offset = 5;
  209. if (match_segments(data, len, sample->data, sample->offset,
  210. sample->size, pos, match_offset, match_len) == 0) {
  211. *match_sample = sample->sample_number;
  212. /* Next time, look for matches at this offset, with a little
  213. * margin to this match. */
  214. sample->offset = *match_offset + *match_len + 5;
  215. if (sample->offset + 10 >= sample->size)
  216. sample_queue_pop(queue); /* Not enough useful data left */
  217. return 0;
  218. }
  219. if (sample->offset < 10 && sample->size > 20) {
  220. /* No match found from the start of the sample,
  221. * try from the middle of the sample instead. */
  222. sample->offset = sample->size/2;
  223. } else {
  224. /* No match for this sample, remove it */
  225. sample_queue_pop(queue);
  226. }
  227. }
  228. return -1;
  229. }
  230. static void output_immediate(const uint8_t *data, int size,
  231. AVIOContext *out, int *entries)
  232. {
  233. while (size > 0) {
  234. int len = size;
  235. if (len > 14)
  236. len = 14;
  237. avio_w8(out, 1); /* immediate constructor */
  238. avio_w8(out, len); /* amount of valid data */
  239. avio_write(out, data, len);
  240. data += len;
  241. size -= len;
  242. for (; len < 14; len++)
  243. avio_w8(out, 0);
  244. (*entries)++;
  245. }
  246. }
  247. static void output_match(AVIOContext *out, int match_sample,
  248. int match_offset, int match_len, int *entries)
  249. {
  250. avio_w8(out, 2); /* sample constructor */
  251. avio_w8(out, 0); /* track reference */
  252. avio_wb16(out, match_len);
  253. avio_wb32(out, match_sample);
  254. avio_wb32(out, match_offset);
  255. avio_wb16(out, 1); /* bytes per block */
  256. avio_wb16(out, 1); /* samples per block */
  257. (*entries)++;
  258. }
  259. static void describe_payload(const uint8_t *data, int size,
  260. AVIOContext *out, int *entries,
  261. HintSampleQueue *queue)
  262. {
  263. /* Describe the payload using different constructors */
  264. while (size > 0) {
  265. int match_sample, match_offset, match_len, pos;
  266. if (find_sample_match(data, size, queue, &pos, &match_sample,
  267. &match_offset, &match_len) < 0)
  268. break;
  269. output_immediate(data, pos, out, entries);
  270. data += pos;
  271. size -= pos;
  272. output_match(out, match_sample, match_offset, match_len, entries);
  273. data += match_len;
  274. size -= match_len;
  275. }
  276. output_immediate(data, size, out, entries);
  277. }
  278. /**
  279. * Write an RTP hint (that may contain one or more RTP packets)
  280. * for the packets in data. data contains one or more packets with a
  281. * BE32 size header.
  282. *
  283. * @param out buffer where the hints are written
  284. * @param data buffer containing RTP packets
  285. * @param size the size of the data buffer
  286. * @param trk the MOVTrack for the hint track
  287. * @param pts pointer where the timestamp for the written RTP hint is stored
  288. * @return the number of RTP packets in the written hint
  289. */
  290. static int write_hint_packets(AVIOContext *out, const uint8_t *data,
  291. int size, MOVTrack *trk, int64_t *pts)
  292. {
  293. int64_t curpos;
  294. int64_t count_pos, entries_pos;
  295. int count = 0, entries;
  296. count_pos = avio_tell(out);
  297. /* RTPsample header */
  298. avio_wb16(out, 0); /* packet count */
  299. avio_wb16(out, 0); /* reserved */
  300. while (size > 4) {
  301. uint32_t packet_len = AV_RB32(data);
  302. uint16_t seq;
  303. uint32_t ts;
  304. data += 4;
  305. size -= 4;
  306. if (packet_len > size || packet_len <= 12)
  307. break;
  308. if (data[1] >= 200 && data[1] <= 204) {
  309. /* RTCP packet, just skip */
  310. data += packet_len;
  311. size -= packet_len;
  312. continue;
  313. }
  314. if (packet_len > trk->max_packet_size)
  315. trk->max_packet_size = packet_len;
  316. seq = AV_RB16(&data[2]);
  317. ts = AV_RB32(&data[4]);
  318. if (trk->prev_rtp_ts == 0)
  319. trk->prev_rtp_ts = ts;
  320. /* Unwrap the 32-bit RTP timestamp that wraps around often
  321. * into a not (as often) wrapping 64-bit timestamp. */
  322. trk->cur_rtp_ts_unwrapped += (int32_t) (ts - trk->prev_rtp_ts);
  323. trk->prev_rtp_ts = ts;
  324. if (*pts == AV_NOPTS_VALUE)
  325. *pts = trk->cur_rtp_ts_unwrapped;
  326. count++;
  327. /* RTPpacket header */
  328. avio_wb32(out, 0); /* relative_time */
  329. avio_write(out, data, 2); /* RTP header */
  330. avio_wb16(out, seq); /* RTPsequenceseed */
  331. avio_wb16(out, 0); /* reserved + flags */
  332. entries_pos = avio_tell(out);
  333. avio_wb16(out, 0); /* entry count */
  334. data += 12;
  335. size -= 12;
  336. packet_len -= 12;
  337. entries = 0;
  338. /* Write one or more constructors describing the payload data */
  339. describe_payload(data, packet_len, out, &entries, &trk->sample_queue);
  340. data += packet_len;
  341. size -= packet_len;
  342. curpos = avio_tell(out);
  343. avio_seek(out, entries_pos, SEEK_SET);
  344. avio_wb16(out, entries);
  345. avio_seek(out, curpos, SEEK_SET);
  346. }
  347. curpos = avio_tell(out);
  348. avio_seek(out, count_pos, SEEK_SET);
  349. avio_wb16(out, count);
  350. avio_seek(out, curpos, SEEK_SET);
  351. return count;
  352. }
  353. int ff_mov_add_hinted_packet(AVFormatContext *s, AVPacket *pkt,
  354. int track_index, int sample)
  355. {
  356. MOVMuxContext *mov = s->priv_data;
  357. MOVTrack *trk = &mov->tracks[track_index];
  358. AVFormatContext *rtp_ctx = trk->rtp_ctx;
  359. uint8_t *buf = NULL;
  360. int size;
  361. AVIOContext *hintbuf = NULL;
  362. AVPacket hint_pkt;
  363. int ret = 0, count;
  364. if (!rtp_ctx)
  365. return AVERROR(ENOENT);
  366. if (!rtp_ctx->pb)
  367. return AVERROR(ENOMEM);
  368. sample_queue_push(&trk->sample_queue, pkt, sample);
  369. /* Feed the packet to the RTP muxer */
  370. ff_write_chained(rtp_ctx, 0, pkt, s);
  371. /* Fetch the output from the RTP muxer, open a new output buffer
  372. * for next time. */
  373. size = avio_close_dyn_buf(rtp_ctx->pb, &buf);
  374. if ((ret = ffio_open_dyn_packet_buf(&rtp_ctx->pb,
  375. RTP_MAX_PACKET_SIZE)) < 0)
  376. goto done;
  377. if (size <= 0)
  378. goto done;
  379. /* Open a buffer for writing the hint */
  380. if ((ret = avio_open_dyn_buf(&hintbuf)) < 0)
  381. goto done;
  382. av_init_packet(&hint_pkt);
  383. count = write_hint_packets(hintbuf, buf, size, trk, &hint_pkt.dts);
  384. av_freep(&buf);
  385. /* Write the hint data into the hint track */
  386. hint_pkt.size = size = avio_close_dyn_buf(hintbuf, &buf);
  387. hint_pkt.data = buf;
  388. hint_pkt.pts = hint_pkt.dts;
  389. hint_pkt.stream_index = track_index;
  390. if (pkt->flags & AV_PKT_FLAG_KEY)
  391. hint_pkt.flags |= AV_PKT_FLAG_KEY;
  392. if (count > 0)
  393. ff_mov_write_packet(s, &hint_pkt);
  394. done:
  395. av_free(buf);
  396. sample_queue_retain(&trk->sample_queue);
  397. return ret;
  398. }
  399. void ff_mov_close_hinting(MOVTrack *track) {
  400. AVFormatContext* rtp_ctx = track->rtp_ctx;
  401. uint8_t *ptr;
  402. av_freep(&track->enc);
  403. sample_queue_free(&track->sample_queue);
  404. if (!rtp_ctx)
  405. return;
  406. if (rtp_ctx->pb) {
  407. av_write_trailer(rtp_ctx);
  408. avio_close_dyn_buf(rtp_ctx->pb, &ptr);
  409. av_free(ptr);
  410. }
  411. avformat_free_context(rtp_ctx);
  412. }